Mesuti Mesuti -4 years ago 122
jQuery Question

Cascade Select Boxes with jQuery

i want to cascading with html select boxes and jQuery ajax posts. when i select an option it send own value to another file and get json values. yes i do this with ajax post. but in the callback function i will add another select box set all of jSON data. and this i do is correctly. but when i select an option from added select box jQuery 'change' event not handling this new select box and eventually doesn't work other functions.

My jQuery codes are follow:

$(document).ready(function(){

$("#kategoriler select").on('change',function(e){

var catID = $(this).val();

if($(this).next().is("select")){
$(this).nextAll("select").remove();
}

console.log($(this));
$.ajax({
async: false,
type: "POST",
url: "ajax_cate_add",
data: "catID=" + catID,

success: function(data){

if(data.length > 0){

var $parent = $("#kategoriler select:last").after("<select></select>").next();

for(var i = 0; i < data.length; i++){
$parent.append("<option value=" + data[i].id + ">" + data[i].tr_adi + "</option>");
}
}
}
});
});
});


Start HTML codes are follow:

<div id="kategoriler">
<select>
<option value="8">Rezervasyon</option>
<option value="7">E-Concierge</option>
<option value="6">Özel F?rsatlar</option>
<option value="5">Safira SPA &amp; Sa?l?k</option>
<option value="4">Toplant? &amp; Davetler</option>
<option value="3">Yeme &amp; ?çme</option>
<option value="2">Odalar &amp; Süitler</option>
<option value="1">Genel Bak??</option>
</select>
</div>


but in the console when i type follow code it's running:

$("select").change(function(){
alert(2);
});


from root select box select an option and after above code i type in console and select an option from new select box this codes did work and show alert message.

Answer Source

At the time of your binding i.e when you are creating change handler, the element (select element) doesn't exist in the DOM (as it is being generated dynamically). So it binds no change handlers as there is no element to bind to. As such, one simple solution would be to use delegation. Now, the beauty of using delegation is that no matter when the element is created, the handler gets assigned to the element. This should do the trick for you.

$(document).on('change','select', function(){
    alert('test');
});

PS:You should try and use delegation whenever you have to create element on the go (dynamically).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download