Sunil Sunil - 1 year ago 87
jQuery Question

Assign a click event function to multiple elements in jQuery?

I have multiple checkboxes on a page whose id starts with


Id of rows could be checkrow1 or checkrow2 or checkrow21 etc.

I want to assign the click event function to each of these checkboxes.

I tried the following but it doesn't seem to work. What is jQuery code to do this?

$('input[id^="checkrow"]').click(function () {

The above code works. The reason why I was not getting the handler attached to click event was because the check-boxes did not exist when above code was executed. I was using a virtualized HTML5 grid in which the checkboxes were only created in 'Databound' event of the third-party control I was using. Once I put the above code in 'Databound' event then it worked fine.

Answer Source

Let me guess, those elements are created dynamically after the DOM is ready.

use on - a delegate event.

$('parentSelector').on('click', 'input[id^="checkrow"]', func);

And of course make sure your code lies inside the DOM ready callback.