4

I've got some code that I'd like to run on every single checkbox on my page within a table, but I'm not sure of the best way to do this? I've tried something like this but it didn't work :(

$(document).ready(function() {

    function whatever (elem) {
        var $elem = elem;
        $elem.val('test');
    }

    $('table tr td :checkbox').(function() {
        whatever($(this));
    }

});

Any help would be fantastic, at a bit of a loss with this! Thanks :)

1
  • 3
    You can select an answer as the correct answer by clicking the checkmark. Commented Aug 6, 2009 at 21:27

2 Answers 2

8

Use $.each();

$.each($('table tr td :checkbox'), function()
    {
       // Code
    });

To access the checkbox you are currently working on in the loop, use this.

$.each($('table tr td :checkbox'), function()
    {
       $(this).hide();
    });
Sign up to request clarification or add additional context in comments.

Comments

1

Check $().each().

And by the way, foo.(bar) is not valid Javascript syntax.

4 Comments

Thanks for the info, sorry to be stupid but can you explain where I used the foo.(bar) thing please? Thanks :)
Actually, it is good you ask :). In the following (copied from your code, rearranged to fit on a single line): $('table tr td :checkbox').(function() { whatever($(this)); }. In this case foo is $('...') and bar is function() { ... }.
Ahh! Thank you! That's a very handy explanation, as I've often seen 'foo' and 'bar' and didn't realise what they meant until now!
They are simply placeholders. Instead of having to write a long piece of code to make a point, I used placeholders. They are also used for names of variables or classes when you just want to explain an abstract idea.

Your Answer

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