jQuery does not see my dynamically loaded checkboxes
I have written a script that will load a series of products into a div tag.
I now want to be able to filter those products using a series of checkboxes.
jquery makes a $post to an ASP page that returns an XML dataset. The first element of the data set contains a list of manufacturers in this format ara|dai|sid|alp etc. The second element contains the manufacturer names of the codes above.
I then use this script to build a list of checkboxes into a div tag.
var mc = new Array();
mc = $("manCodes",xml).text().split(",");
var manTitles = new Array();
manTitles = $("manTitles",xml).text().split(",");
for ( var i=0, len=mc.length; i<len; ++i ){
m += '<span><input type="checkbox" value="' + mc[i] + '" name="man[]" id="man_'+i+'" />' + manTitles[i] +'</span>'//mc[i];
}
manufacturers = '<div id="filter" class="man">FILTER<br />' + m + '</div>';
$(".formSelect").append(manufacturers);
This works a treat and then in the Document Ready section I have a code segment that looks for any cl开发者_开发百科ick on a checkbox:
$(document).ready( function() {
$("input:checkbox").click(function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});
This is where my code falls over because any click on any checkbox is not working. Its almost like JQuery cannot see these checkboxes that it has created.
Can anybody please help how to resolve this problem please?
Cheers Graham
You need event delegation, otherwise the event handler will not fire for dynamically inserted/removed elements. .live
or .delegate
are two options.
$("input:checkbox").live("click", function() {
// implementation
});
or better:
$("form").delegate("input:checkbox", "click", function() {
// implementation
});
use jQuery.live() to capture events from dynamically added elements.
Attach a handler to the event for all elements which match the current selector, now and in the future.
$("input:checkbox").live("click", function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
Try:
$(document).ready( function() {
$("input:checkbox").live("click",function() {
loadXML($("#sortOrder option:selected").val(),$("#limitBy option:selected").val(),$("#productGroup").val());
});
});
精彩评论