Reputation: 169
I am trying to have two dropdown boxes. The second one gets populated based on the selection in the first dropdown. The first dropdown works fine, but the second dropdown does not. Can some one help me with this?
HTML:
<div class="container-fluid">
<div class="row">
<div class="col-sm-2 col-md-2 col-lg-2">
<div class="dropdown" id="villageselector">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Village <span class="caret"></span></button>
<ul class="dropdown-menu">
</ul>
</div>
</div>
<div class="col-sm-2 col-md-2 col-lg-2">
<div class="dropdown" id="farmerselector">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Farmer <span class="caret"></span></button>
<ul class="dropdown-menu">
</ul>
</div>
</div>
</div>
</div>
JS:
//Populate the first dropdown
$.each(villagelist, function() {
$('#villageselector ul').append('<li><a data-villagename="'+ this.village+'" data-id = "'+this.id+'">' + this.village + '</a></li>');
});
//Add selector on the first dropdown
$('#villageselector a').click(function(){
selectedvillagename = $(this).data().villagename;
//Populate the second dropdown, based on the selection on the first dropdown
$.each(villagelist, function() {
if (this.village === selectedvillagename) {
for(i=0; i<this.farmernames.length; i++){
$('#farmerselector ul').append('<li><a data-farmername="'+ this.farmernames[i]+'" data-id = "'+i+'">' + this.farmernames[i] + '</a></li>');
}
}
});
});
$('#farmerselector a').click(function(){
//the list gets populated, but on selecting one of them, the code never reachers here
});
Upvotes: 0
Views: 28
Reputation: 1931
You need to change the $('#farmerselector a')
click handler to a delegated event handler $(document).on('click', '#farmerselector a', function () //...
See https://learn.jquery.com/events/event-delegation/ for more info.
Upvotes: 1