Andrus
Andrus

Reputation: 27931

How to bind to checkbox checked event

How to run javascript code if checkbox is checked?

checkbox is defined as

    <input type="checkbox" id="Maksja_piiratudes" name="Maksja_piiratudes" 

onfocus="if(typeof this.ischanged=='undefined') this.ischanged=false" onblur="summarefresh()" onclick="dataChanged(this)">

I tried

$(function () {
  $("#Maksja_piiratudes").on("change", function() {

alert('checkbox is checked');

});  // end on change
}); // end $

But this runs also if checkbox is unchecked. How to run code only if checkgox is selected ?

Bootstrap 3, jquery, jquery UI are used.

Upvotes: 2

Views: 9743

Answers (2)

Kai
Kai

Reputation: 1225

You can use the checked property of an checkbox input.

$(function()
{
    $('#Maksja_piiratudes').on('change', function()
    {
        if (this.checked)
        {
            alert('checkbox is checked');
        }
    });
});

Edit:

I prefer the vanilla style more.. so just in case someone needs it:

document.querySelector('#Maksja_piiratudes')
        .addEventListener('change', function()
{
    if (this.checked)
    {
        alert('checkbox is checked!');
    }
}, false);

Upvotes: 5

Mario Rawady
Mario Rawady

Reputation: 871

Try This

$(function () {
    $("#Maksja_piiratudes").on("change", function() {    
       if ($(this).prop("checked") == true) {
           alert('checkbox is checked');
       } //end if
    });  // end on change
}); // end $

If you want to make it global for all checkboxes use the below:

$(function () {
    $("input[type='checkbox']").on("change", function() {    
       if ($(this).prop("checked") == true) {
           alert('checkbox is checked');
       } //end if
       else {
           alert('checkbox is unchecked');
       }
    });  // end on change
}); // end $

Upvotes: 1

Related Questions