Reputation: 171
I need to create dynamic drop down. I can load data for second drop down based on the value of first one. After that I need to add new rows of drop down as well. I can add new drop down rows. But I can not dynamically load value for newly added drop downs.
This is my jQuery to load data for second drop down:
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function() {
alert('ok');
var state = $("#state :selected").text();
$.ajax({
url:"http://localhost:8888/ajax/search_attendee.php",
type:"post",
data:'state='+ state,
dataType: "html",
success:function(data){
$("#trainer").html(data);
}
});
});
});
</script>
This is jQuery to load new rows. I can add rows by this function. But I can not load data for my second drop down. Can anybody help me to do this?
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p>'+
'<table id="datatable"><tr><td width="220"></td><td>'+
'<select name="state_' + i +'" id="state">'+
'<option value="0">Select State</option>'+
'<option value="1">QLD</option>'+
'<option value="2">NSW</option>'+
'<option value="3">VIC</option>'+
'<option value="4">WA</option>'+
'<option value="5">ACT</option>'+
'<option value="6">NT</option>'+
'<option value="7">SA</option>'+
'<option value="8">TAS</option>'+
'</select>'+
'<select name="trainer_' + i +'" id="trainer"><option>Select Trainer</option></select>'+
'<a href="#" id="remNew">Remove</a></td></tr></table></p>').appendTo(addDiv);
i++;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
});
});
</script>
Upvotes: 0
Views: 111
Reputation: 36531
you need to delegate your event to closest static parent usign on
for dynamically added element. which is #state
in your case
$(document).on('change','#state',function() {
alert('ok');
var state = $("#state :selected").text();
.....
you might also need to change your live()
to on()
if you are using latest jquery version i.e. 1.6+
since live is deprecated
$(document).on('click','#addNew',function() {
....
$(document).on('click','#remNew', function() {
...
this works however, delegating your dynamic element to closest static element which is present in the document at the time of insertion is better than to use the document itself performance wise.
Upvotes: 1