最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to bind to checkbox checked event - Stack Overflow

programmeradmin9浏览0评论

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.

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.

Share Improve this question edited Oct 7, 2017 at 16:34 Andrus asked Oct 7, 2017 at 16:30 AndrusAndrus 28k67 gold badges214 silver badges396 bronze badges 1
  • One line was missing. I edited question and added missing line – Andrus Commented Oct 7, 2017 at 16:35
Add a ment  | 

2 Answers 2

Reset to default 5

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

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 $
发布评论

评论列表(0)

  1. 暂无评论