I am initializing a row of buttons using jquery on $(window).load with this code:
$(window).load(function() {
var numButt = 0;
randArr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
var Row = $(document.createElement('div')).attr("id", 'row1');
Row.appendTo(".rows");
for (;numButt < 22; numButt++){
var newBut = $(document.createElement('span')).attr("id", 'but' + numButt);
newBut.html('<input type="button" name="But' + numButt + '" id="case' + (numButt+1) + '" value= ' + randArr[numButt] + '>');
newBut.appendTo($(".rows").find("#row1"));
}
}
);
Then, I have this to handle clicks:
$(document).ready(function(){
$(".rows > div > span > input").click(function () {
alert(this.id);
});
});
And after the end of the script block:
<div class='rows'>
<div id='lol'>
<span>
<input type = 'button' name = 'test1' id = 'test1' value = 'test1'>
</span>
<span>
<input type = 'button' name = 'test2' id = 'test2' value = 'test2'>
</span>
</div>
</div>
So, topologically, the two test buttons and one of the 22 buttons I initialized should be the same. But it only recognizes my click on the two test buttons. What am I doing wrong?
Since the other buttons are being added dynamically you have to delegate your events. You can do this with on()
.
$('.rows').on('click', 'input', function () {
alert(this.id);
});