Question

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?

Was it helpful?

Solution

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);
});

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top