7

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/

3
  • 2
    First you need to add checked attribute and then try..it will alert 'it works' => try jsfiddle.net/8vf3uLef 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. Commented May 18, 2016 at 13:49
  • It's working fine - your check box is not checked, so you don't get the alert. Commented May 18, 2016 at 14:09

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

7

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')
  }
})

Comments

1

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

Comments

1

I think this is the most simple way:

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

Comments

-2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.