0

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.

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

This is not answering the question.
True, but it is actually what should be done. Possibly with a delegate if he adds the checkboxes dynamically.
@ThiefMaster. I'm not sure it should be done this way. there is nothing wrong with using the starts with attributes selector, class selector are fine, but the original use of class is CSS... Anyway it still doesn't answer the question, nor even try to do so. :(
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.