Sunil
Sunil

Reputation: 21396

Assign a click event function to multiple elements in jQuery?

I have multiple checkboxes on a page whose id starts with checkrow.
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 () {
    alert('1')
});

UPDATE: 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.

Upvotes: 0

Views: 3274

Answers (3)

netdjw
netdjw

Reputation: 5997

An other solution: find checkboxes, after select id=checkrow*, then add a click event:

$('input[type=checkbox]').each(function() {
    if ( this.id.match(/^checkrow\d+/) ) {
        $(this).click(function() {
            // do what you want 
        });
    }
});

Upvotes: 1

gdoron
gdoron

Reputation: 150253

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.

Upvotes: 4

Throttlehead
Throttlehead

Reputation: 1945

Use a class for the check boxes and then target the class name with a dot. Each checkbox will have an attribute "class='checkbox'".

$('.checkbox').click(function(){
    alert('Check clicked.');
});

Upvotes: 3

Related Questions