1

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?

Squall Leohart
  • 657
  • 2
  • 8
  • 20

2 Answers2

2

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);
});
elclanrs
  • 92,861
  • 21
  • 134
  • 171
  • This looks great, you may want to add the qualifier of input[type='button']. Otherwise, the .on property should work. Is there any reason why you may need to use .click? If you're using jQuery 1.7 or later .on should work, 1.6 .delegate might be the way to go on 1.6 or before, .live on 1.4 or before. – jamesbar2 Jul 31 '12 at 03:48
  • Thank you. just a follow up question: How come I no longer need '.rows > div >span > input'? or '.rows > div > span' at least – Squall Leohart Jul 31 '12 at 04:58
  • You just need what's strictly necessary, in this case `.rows` and `input`, all other stuff that's in between is trivial. – elclanrs Jul 31 '12 at 05:00
  • 1
    Because the `span` is dynamic too, you'd need to write `$('.rows > div').on('click', 'span > input', function () {` but again, this is unnecessary. – elclanrs Jul 31 '12 at 05:13
0

Oops. I read your question in a reverse sorta way. Anyway, I suspect there is a problem with the way you're creating elements on the DOM as well as emitting html markup interchangeably. Instead, try composing all the html markup for the 20+ buttons, and the do a one-time emit of that markup. Something like this: $("#div1").html(buttons.split('')) // where buttons is an array of strings used to compose the html of buttons. Then your .click should work, because i don't see anything obviously wrong with it.

AlvinfromDiaspar
  • 6,611
  • 13
  • 75
  • 140