Reputation: 349
I'm creating a table with a list of check boxes with values reading out of JSON file.
Every time a check box is clicked i want to execute the function count checked. Unfortunately JQuery $("input[type=checkbox]")
doesn't recognize the dynamic created check boxes. The only check box working is the one written directly in body code block.
How can I say JQuery to check for newly created check boxes?
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#get").click(function(){
$.getJSON("data.txt",function(result){
$("#b").append('<form><table></table></form>');
$.each(result['effectNames'], function(i, field){
$("table").append('<tr><td>' + field + '</td><td><input type="checkbox" value="' + i + '" ></td></tr>');
});
});
});
var countChecked = function() {
var n = $( "input:checked" ).length;
$( "#a" ).text( n + (n === 1 ? " is" : " are") + " checked!" );
};
countChecked();
$( "input[type=checkbox]" ).on( "click", countChecked );
});
</script>
</head>
<body>
<button id="get">Get JSON data</button>
<input type="checkbox" name="r" value="Hourly" checked="checked">
<div id="b"></div>
<div id="a"></div>
</body>
</html>
Upvotes: 0
Views: 1861
Reputation: 388316
you need to use event delegation here
$("#b").on( "click", "input[type=checkbox]", countChecked );
Upvotes: 4