-1

I want to check if a checkbox is checked. I tried the following 4 methods in jQuery, but none is working:

$('#first').change(function() {
  if ($(this).is(':checked')) {
    console.log('checked1');
    // perform action
  }

  if ($('#first:checked').length) {
    // perform action
    console.log('checked2');
  }

  if ($('#first').is(':checked')) {
    // perform action
    console.log('checked3');
  }

  if ($('#first').attr('checked')) {
    // perform action
    console.log('checked4');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="" id="first">
WOUNDEDStevenJones
  • 5,150
  • 6
  • 41
  • 53
  • Does this answer your question? [How do I check whether a checkbox is checked in jQuery?](https://stackoverflow.com/questions/901712/how-do-i-check-whether-a-checkbox-is-checked-in-jquery) Your example is working as expected (except for the 4th conditional). – WOUNDEDStevenJones Nov 18 '21 at 14:29
  • 2
    The snippet in your question is working absolutely fine. If it's not working for you, then you've made a mistake in your local version - not including jQuery.js in the page perhaps, or not using document.ready. – Rory McCrossan Nov 18 '21 at 14:33
  • @WOUNDEDStevenJones no because it suggests what I already tried. – user17281121 Nov 18 '21 at 14:33
  • @Sebastian why would that be needed? The OP isn't using ES6 syntax – Rory McCrossan Nov 18 '21 at 14:33
  • @Sebastian jQuery injects `this` for you into the function. – Peter Krebs Nov 18 '21 at 14:38

1 Answers1

0

jQuery uses prop() now for attributes: https://api.jquery.com/prop/
The documentation states it will update with checked checkboxes as well.

All your examples are working for me. Updated the .prop call in the snippet below.

$('#first').change(function() {
  if ($(this).is(':checked')) {
    console.log('checked1');
    // perform action
  }

  if ($('#first:checked').length) {
    // perform action
    console.log('checked2');
  }

  if ($('#first').is(':checked')) {
    // perform action
    console.log('checked3');
  }

  if ($('#first').prop('checked')) {
    // perform action
    console.log('checked4');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="" id="first">
Peter Krebs
  • 3,831
  • 2
  • 15
  • 29