views:

846

answers:

2

Hey,

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 :)

+4  A: 

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();
    });
Chacha102
Ahh that looks great, thank you! I will give this a try :)
+1  A: 

Check $().each().

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

Sinan Taifour
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() { ... }`.
Sinan Taifour
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.
Sinan Taifour
Ah I see! That makes sense, thanks :)