Reputation: 147
I am using jQuery to create two dropdowns dynamically where on change of the first one determines what will be put in the second one as follows:
$("#add").click(function () {
var id = Date.now();
var text = " <div class='row' id='" + id + "'><br /> \
<div class='col-md-3'><select class='listOptions' id='myoptions[" + id + "].user'>" + listOptions + "</select></div> \
<div class='col-md-3'><select class='secondOptions' id='myoptions[" + id + "].cars'></select></div></div>";
this will create two dropdowns in this format:
myoptions[1405087264136].user
myoptions[1405087264136].cars
Accessing the first dropdown is easy through
$(document).on("change", '.listOptions', function () {...}
Now the issue is accessing the second one has baffled me:
I have tried this:
currentid = $(this).attr('id').substr(0, 24) + ".cars";
But either of these 2 lines return 0
alert($("#" + currentid).length);
alert(document.getElementById(currentid).length);
Note: for some reason, in the console, I am able to access the second option
What am I missing?
Upvotes: 1
Views: 76
Reputation: 337610
You can use a combination of closest
(to get the parent) and find
to get the related .secondOptions
element. Try this:
$(document).on("change", '.listOptions', function () {
var currentid = $(this).closest('.row').find('.secondOptions').val();
});
Using DOM traversal in this way means you don't need to worry about unique or incremental identifiers.
Upvotes: 2