Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bool value from checkbox in javascript / jquery?

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/

like image 396
Lxs29 Avatar asked Dec 24 '22 05:12

Lxs29


1 Answers

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

like image 147
J. Titus Avatar answered Dec 26 '22 19:12

J. Titus