admin管理员组

文章数量:1201410

I'm trying to see if a checkbox is checked or not with a simple function. It doesn't seem to be working, here's the code:

HTML:

<form>
  <input type="checkbox" id="check" />
</form>

JS:

$(document).ready(function() {
  if ($('#check').is(":checked")) {
    alert('it works')
  }
});

JSFiddle: /

I'm trying to see if a checkbox is checked or not with a simple function. It doesn't seem to be working, here's the code:

HTML:

<form>
  <input type="checkbox" id="check" />
</form>

JS:

$(document).ready(function() {
  if ($('#check').is(":checked")) {
    alert('it works')
  }
});

JSFiddle: https://jsfiddle.net/5h58mx1h/

Share Improve this question asked May 18, 2016 at 13:47 Lxs29Lxs29 1751 gold badge2 silver badges14 bronze badges 3
  • 2 First you need to add checked attribute and then try..it will alert 'it works' => try jsfiddle.net/8vf3uLef – Dhara Parmar Commented May 18, 2016 at 13:48
  • this works, if you want to get a message, when checked is changed, go for the changed event. – Nils Commented May 18, 2016 at 13:49
  • It's working fine - your check box is not checked, so you don't get the alert. – fdomn-m Commented May 18, 2016 at 14:09
Add a comment  | 

5 Answers 5

Reset to default 9

Your code only runs once - when document is ready. You need to attach an event listener to the checkbox and check when it changes:

$(document).ready(function() {
  $('#check').change(function() {
    if ($(this).is(":checked")) {
      alert('it works');
    }
  });
});

Fiddle

You don't need jQuery. An <input type="checkbox"> has a checked attribute, which you can use like this:

document.addEventListener("DOMContentLoaded", () => {
  if (document.getElementById("check").checked) {
    alert('it works')
  }
})

It should be work:

 $(document).ready(function () {
        var ckbox = $('#checkbox');

        $('input').on('click',function () {
            if (ckbox.is(':checked')) {
                alert('You have Checked it');
            } else {
                alert('You Un-Checked it');
            }
        });
    });

jsFiddle

I think this is the most simple way:

  if ($('#check').checked) {
    alert('it works');
  }

Replace your HTML to this

<form>
  <input type="checkbox" id="check" checked />
</form>

This will work for you. Because you don't checked checkbox yet that's why not alert.

本文标签: How to get bool value from checkbox in javascriptjqueryStack Overflow