tags:

views:

41

answers:

3

Here's a little jQuery function that does what I want when a checkbox is clicked, but I have a basic gap in my knowledge:

How to register this so that it deals with checkboxes that are already clicked when the page loads?

(Edit: Sorry, to those who already answered the question, but i've edited this to make it more clear)

$(document).ready(function() {
  $('fieldset input:checkbox').click(function() {
    if ($(this).attr('name') == 'foo') {
      if ($(this).attr('checked')) {
        // hide checkbox 'bar'
      }
      else {
        // show checkbox 'bar'
      }
    }
  }
});

If I use .trigger('click'), it clicks (or unclicks) all the boxes on page load.

I can think of a few ways to do this that would involve repeating portions of the code, but I just know that jQuery already has an elegant answer for this...

+1  A: 

You can put that code into a function and call the function immediately.

For example:

function handleCheckbox() {
    if ($(this).attr('name') == 'foo') {
      // hide checkbox 'bar'
    }
    else {
      // show checkbox 'bar'
    }
}

$(function() {
    $('fieldset :checkbox').each(handleCheckbox).click(handleCheckbox);
});
SLaks
This will call the click function on all of them and toggle if they are checked or not. He wants it only to trigger on the ones that are checked on load.
PetersenDidIt
@petersendidit: If that's what he wants, he _needs_ to call `$(this).is(':checked')` in the handler. (In case the user clicks the checkbox twice)
SLaks
You should avoid using `$(function(){...`. It's not supported in jQuery 1.4
Sam
@Sam `$(function(){});` is supported. Its `$()` as a short cut to `$(document)` that is not.
PetersenDidIt
I stand corrected. Thanks @petersendidit.
Sam
A: 

like this?

$(function() {
  $('fieldset input:checkbox').click(function() {
    if ($(this).attr('name') == 'foo') {
      // hide checkbox 'bar'
    }
    else {
      // show checkbox 'bar'
    }
  }).filter(":checked").click();
})

After seeing another answer i don't think the above is what you want. +1 to the other guy.

:-)

David Murdoch
+2  A: 
$(document).ready(function() {
   $('fieldset input:checkbox').click(handleClick)
     .filter(':checked').each(handleClick);
});

function handleClick(){
    if ($(this).attr('name') == 'foo') {
      // hide checkbox 'bar'
    }
    else {
      // show checkbox 'bar'
    }
}

You might need to add some logic in your handleClick function to make sure you know what state the checkbox is in. You can do this by calling $(this).is(':checked');

PetersenDidIt
+1 to you for completely understanding the ?.
David Murdoch
If this is what he wants to do, his code won't do what he wants if the user _unchecks_ a checkbox.
SLaks
@SLaks very true, updated my answer to point out that fact and show him how to check the state.
PetersenDidIt
thanks, sorry for the lack of clarity in the question and +1 for still getting the right answer.
lazysoundsystem