开发者

How to do an action when a checkbox is checked with jQuery?

I want to do an action when a user checks a checkbox, but I can't get it to work, what am I doing wrong?

开发者_Go百科So basically, a user goes to my page, ticks the box, then the alert pops up.

if($("#home").is(":checked"))
{
      alert('');
}


What you are looking for is called an Event. JQuery provides simple event binding methods like so

$("#home").click(function() {
    // this function will get executed every time the #home element is clicked (or tab-spacebar changed)
    if($(this).is(":checked")) // "this" refers to the element that fired the event
    {
        alert('home is checked');
    }
});


Actually the change() function is much better for this solution because it works for javascript generated actions, such as selecting every checkbox via a script.

$('#home').change(function() {
   if ($(this).is(':checked')) {
      ... 
   } else {
      ...
   }
});


you need to use the .click event described here: http://docs.jquery.com/Events/click#fn

so

$("#home").click( function () {
    if($("#home").is(":checked"))
    {
      alert('');
    }
});


$("#home").click(function() {
    var checked=this.checked;
    if(checked==true)
        {
         // Stuff here
        }
    else
        {
        //stuff here
        }
});


$( "#home" ).change(function() {
    if(this.checked){
        alert("The Check-box is Checked"); // Your Code...
    }else{
        alert("The Check-box is Un-Checked"); // Your Code...
    }
});


for some cases, when you have a dynamic content you can use this code:

$(function() {
  $(document).on('click','#home',function (e) {
    if($(this).is(":checked")){
      alert('Home is checked')
    }else{
      alert('Home is unchecked')
    }
  });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜