Using two modal popups while passing an identifier

UPDATE:

In my investigation, I discovered that a plain input tag without MVC RAZOR works as expected:

<input type="text" class="hiddenid2" /> //WORKED

However, when using the following code, it does not work:

 @Html.Editor("id", "", new { htmlAttributes = new { @class = "hiddenId2" } })

or

 @Html.Editor("id", "", new { @class = "hiddenId2"  })

The issue is perplexing me after meticulously reviewing each line of code. Everything seems correct, but I'm unsure of what else needs to be done in this situation.

The problem I am encountering is:

I need to pass the Id to two modal popups with different Ids and class names. The first modal popup successfully passes the Id, but the second one does not.

First Modal:

//View Link

<a href="/Home/Employee/@item.Id" data-id="@item.Id" 
data-toggle="modal" data-target="#myModal" 
class="modalLink">Load Employee</a>

View:

@using (Html.BeginForm("Employee", "Home", FormMethod.Post))
{

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Record</h4>
                </div>
                <div class="modal-body">
                 @Html.Hidden("id", "", new { @class = "hiddenid" })
                </div>
                <div class="modal-footer">
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
}

JQuery:

$(.modalLink").click(function () {
     var passedID = $(this).data('id');
     $('#id').val(passedID);
     $(".modal-body .hiddenid").val(passedID);
});

Second Modal:

//View Link

<a href="/Home/Employer/@item.Id" data-id="@item.Id" 
data-toggle="modal" data-target="#myModal2" 
class="modalLink2">Load Employer</a>

View:

@using (Html.BeginForm("Employer", "Home", FormMethod.Post))
{

    <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Record</h4>
                </div>
                <div class="modal-body">
                 @Html.Hidden("id", "", new { @class = "hiddenid" })
                </div>
                <div class="modal-footer">
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->
}

JQuery:

$(.modalLink2").click(function () {
     var passedID = $(this).data('id');
     $('#id').val(passedID);
     $(".modal-body .hiddenid").val(passedID);
});

Answer №1

The issue stems from your selector. Both modals have the same $(".modal-body .hiddenid").val(passedID); line, which will always target the first .modal-body .hiddenid element that jQuery discovers, typically the one in your initial modal.

One quick solution is to change the class name of the second modal.

For a live demonstration, check out this example on Codepen

HTML:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<a href="/Home/Employee/@item.Id" data-id="id-number-one" 
data-toggle="modal" data-target="#myModal" 
class="modalLink">Load Employee</a>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">Record</h4>
                </div>
                <div class="modal-body">
                   <input type="text" class="hiddenid"/>
                </div>
                <div class="modal-footer">
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div><!-- /.modal -->




<br>
<a href="/Home/Employer/@item.Id" data-id="id-number-two" 
data-toggle="modal" data-target="#myModal2" 
class="modalLink2">Load Employer</a>

<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Record</h4>
      </div>
      <div class="modal-body">
        <input type="text" class="hiddenid2"/>
      </div>
      <div class="modal-footer">
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

JS:

$(".modalLink").click(function () {
    var passedID = $(this).data('id');
     $('#id').val(passedID);
     $(".modal-body .hiddenid").val(passedID);
});

$(".modalLink2").click(function () {
     var passedID = $(this).data('id');
     $('#id').val(passedID);
     $(".modal-body .hiddenid2").val(passedID);
});

Answer №2

@Ji_in_coding was instrumental in helping me identify why the id was not being passed, leading me to include both class and id successfully.

I managed to resolve this issue by incorporating both id and class attributes.

@Html.Hidden("id", "", new { @class = "hiddenid2", id = "hiddenid2" })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of -= and += operators in JavaScript programming language?

I'm puzzled by the mathematical process behind this JavaScript code, which results in -11. let x = 2; let y = 4; console.log(x -= y += 9) ...

The custom tooltip is not being displayed as intended

I'm currently working on customizing tooltips in angularjs google charts. My goal is to display multiple series data along with some text within the tooltip, similar to the demo showcased here. Specifically, I aim to include the legend and title of th ...

Why is my code throwing an error stating "Unable to assign value to innerHTML property of null"?

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div class="container">Lorem ipsum</div&g ...

api for enhancing images in Laravel app through preview, enlarge, and zoom functionalities

As I work on my website, I aim to display images in a compact space, such as within a 300x300 <div>. What I envision is the ability for users to preview or enlarge these images upon clicking, allowing for a closer and more detailed view. For exampl ...

Achieving Dynamic Center Alignment of Filtered Node in SVG Using D3

I am currently implementing filter functionality for my d3 graph. The goal is to allow users to search for a specific node by label or ID, then re-render the graph to display the entire structure with the filtered node positioned at the center of the SVG e ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: https://i.sstatic.net/WSOJr.png Whenever an option is ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

The data type 'string' cannot be assigned to the type '(url: string) => string'.ts(2322)

I am working with a Material UI copyright component: export default function Copyright(link: string, text: string) { return ( <Typography variant="body2" color="textSecondary" align="center"> {'Copyright © '} <Link co ...

Do you know of a solution to fix the Stylelint error regarding semicolons when using CSS variables?

React.js Css in JS(Emotion) The components above are part of this setup. Here is the configuration for Stylelint: module.exports = { extends: [ "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js", ], ...

What are some ways to enhance the functionality of the initComplete feature in Dat

$('#example').dataTable( { "initComplete": function(settings, json) { alert( 'DataTables has finished its initialisation.' ); } } ); Is there a way to extend the initComplete function for other languages? $.extend( true, $.f ...

Sending a POST request via HTTPS results in a 403 error (Forbidden) being triggered

Utilizing the jQuery fileDownload tool (developed by John Culviner), I am loading dynamically generated DOCX files from a JBoss server using RESTEasy. Both the application and the files are within the same domain. This process works seamlessly when retrie ...

Is it possible to call a REST API in Javascript by passing the username and password as

I have been attempting to use Javascript to call the AwaazDe REST API with a specific username and password, but I'm encountering issues. Below is my code: function authenticateUser(user, password) { var token = user + ":" + password; ...

Restrict the sorting functionality in a jQuery list

I have a project that involves scheduling individuals into different rooms, and I'm using jQuery sortables to accomplish this. The challenge I am facing is that each room has a maximum capacity limit. For example, some rooms can only hold 3 people, wh ...

Is there a way to transform a time string, for instance "8:02 AM", into a sortable field?

I am currently working with a MongoDB database that stores times as strings, and I want to filter queries based on specific time ranges. For instance, the time fields in my database are formatted as "8:02 AM" and "10:20 PM", and I am looking to refine my ...

What is the best way to bring files into your project from a different directory?

Recently, I've been working on an app that consists of a backend repo and 2 frontend repos. Now, I'm facing the challenge of sharing code between these two frontend repos. app/ mySecondApp/ Despite my efforts, I'm unable to successfully imp ...

Using jQuery, how can I add value to every input when the option is changed?

I need help changing the values of all input:text elements based on selections from a select menu. Specifically, I want to change only the matched td.class values from the data-pset attribute inside the <select>. As a beginner in jQuery, I can only ...

The height of each Bootstrap column is equal to the height of its corresponding

I am trying to prevent the column height from being equal to the row height in Bootstrap. Here is my code snippet: <div class="row justify-content-center text-center"> <div class="col-sm-3"></div> <div class="col-sm-9"></d ...

The functionality to disable the ES lint max length rule is malfunctioning

In trying to disable an eslint rule in a TypeScript file, I encountered an issue with a regular expression that exceeded 500 characters. As a result, an eslint warning was generated. To address this, I attempted to add an eslint comment before declaring th ...

Is it possible to use mapDispatchToProps in Redux without mapStateToProps?

As I dissect Redux' todo example to gain a deeper understanding, I came across the concept of mapDispatchToProps. This feature allows you to map dispatch actions as props, which led me to consider rewriting addTodo.js by incorporating mapDispatchToPro ...

JavaScript - The AJAX response is consistently after being undefined

I am encountering an issue with the following functions: function get_non_authorized_bulk_edit_option_values() { var modificable_column_names = get_write_user_values(); alert(modificable_column_names); } The above function is calling this ...