0

I'm trying to write code that displays an alert when a checkbox is checked but it's not working. I have tried different code online but still can't get it to work. Could anyone please help me. Thank you.

<div id="filterBox">
    <input type="checkbox" value="categorya" id="one" />
    <label for="one">One </label>

    <input type="checkbox" value="categorya" id="two" />
    <label for="two">Two </label>

    <input type="checkbox" value="categorya" id="three" />
    <label for="three">Three </label>
</div>
$(document).ready(function() {
    if ($('#one').is(":checked")) {
        console.log("testing");
    }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Ranaz 116
  • 19
  • 5
  • 2
    You need to wrap your checking code in a `.change` handler for the element. The way you have it now, the check runs only once when the document is finished rendering. https://api.jquery.com/change/ – Pekka Nov 22 '16 at 11:19
  • Something like `$("#one").change(function() { .... });` (but still inside the document.ready handler). – Pekka Nov 22 '16 at 11:20
  • Possible duplicate of [jQuery checkbox change and click event](http://stackoverflow.com/questions/7031226/jquery-checkbox-change-and-click-event) – GiuServ Nov 22 '16 at 11:29

5 Answers5

1

You are missing the click event. You can try as follows.

$(document).ready(function(){
  $('input[type="checkbox"]').click(function(){
    if ($('#one').is(":checked")) {
        console.log("testing");
    }
  });
});

Or you can use a change event as follows as suggested by @Rory McCrossan.

$(document).ready(function(){
  $('input[type="checkbox"]').change(function(){
    if ($('#one').is(":checked")) {
        console.log("testing");
    }
  });
});

Working JSFiddle sample is here

Sibeesh Venu
  • 18,755
  • 12
  • 103
  • 140
0

you may use

 $(document).ready(function(){
    $("#one").change(function(){
      if ( $(this).prop('checked') == true ) {
        console.log("testing");
      }
    });
  });
sainanky
  • 507
  • 4
  • 13
0

Or instead of creating 3 different conditions,

you can use this one for all

add this javascript

$('input[type="checkbox"]').click(function(){

if ($('#'+this.id).is(":checked")) {
    console.log(this.id + " is checked");
}
});
Punit
  • 450
  • 3
  • 11
0
$(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
       if (this.checked) {             
          alert(this.id);
       }
   });
});
Jenny
  • 663
  • 4
  • 8
0

Try this, you need to attach a click event to your checkbox, also following will avoid specific checkbox check. Each checkbox click event will be handled.

$(document).ready(function() {
   //attach click on each checkbox
   $('input[type=checkbox]').on('click', function(){
       // if the current checkbox is checked then you can do what you want!
       if ($(this).is(":checked")) {
        console.log("testing");
       }
   });
});
ScanQR
  • 3,740
  • 1
  • 13
  • 30