Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

So basically, a user goes to my page, ticks the box, then the alert pops up.

if($("#home").is(":checked"))
{
      alert('');
}
like image 941
Keith Donegan Avatar asked Dec 06 '09 02:12

Keith Donegan


2 Answers

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');
    }
});
like image 123
Joel Avatar answered Oct 24 '22 10:10

Joel


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 {
      ...
   }
});
like image 45
Zoltan Avatar answered Oct 24 '22 09:10

Zoltan