开发者

Triggering jquery event function at page load

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 开发者_StackOverflowpage 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...


$(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');


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


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.

:-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜