checkbox checked and unchecked only if condition applying

Viewed 494

here is my code. I am trying to get alert when checkbox checked and unchecked.

 <html>
 <script src="jquery.min.js"></script>    
 <script>
   $(document).ready(function(){
       $('.checks').change(function(){
          var qn=$(this).attr('id');
          if($('#qn').prop('checked',true))
          {         
             alert('question '+qn+' checked');
          }
          else
          {
             alert('question '+qn+' Unchecked');
          }
    
       });
     });
   </script>
   </html>
    <?php
       for($i=1;$i<=5;$i++)
       {
          echo"<input type='checkbox' id='$i' class='checks' />Question-$i<br>";
       }
       ?>

But when i check or uncheck only if condition is applying. Where i did the mistake

1 Answers

You can use is(":checked") to check if the checkbox is check or not .Also , there is no such id i.e : $('#qn') exist it should be $('#'+qn)..

Demo Code :

$(document).ready(function() {
  $('.checks').change(function() {
    var qn = $(this).attr('id');
    //check if is checked
    if ($('#' + qn).is(":checked")) {
      alert('question ' + qn + ' checked');
    } else {
      alert('question ' + qn + ' Unchecked');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' id='1' class='checks' />Question-1<br>
<input type='checkbox' id='2' class='checks' />Question-2<br>
<input type='checkbox' id='3' class='checks' />Question-3<br>
<input type='checkbox' id='4' class='checks' />Question-4<br>

Related