javascriptjquerycheckedevent-triggers

Jquery auto trigger event on checkbox unchecks the control


Here is my html and javascript, want to auto check on click of button and oncheck want to trigger some more actions. Tried with 'click' and 'change' event

<!DOCTYPE html>
 <html>
 <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
     $(document).ready(function(){


$('#4').on('click', function(){
    $('#1').prop('checked', true).trigger('click');
    $('#2').prop('checked', true).trigger('click');
});

$('#1').on('click', function(){
    if($('#1').is(':checked')){
        $('#3').prop('disabled','disabled');
    }
    else{
    $('#3').prop('disabled','');
    }
         });
       });
 </script>
    </head>
    <body>
    <label>
      <input id="1" type="checkbox" value="">Yes</label><br><br>
         <label>
       <input id="2" type="checkbox" value="">NO</label><br><br>
     <label>
      <input id="3" type="text" value="Hello World">Yes</label><br><br>

     <input id="4" type="button" value="Submit"/><br><br>
      </body>
      </html>

Solution

  • Something like this should get you started.

    var onYesChecked = function() {
      if($('#1').is(':checked')){
        $('#3').prop('disabled',true);
      } else{
        $('#3').prop('disabled',false);
      }
    };
    
    var onNoChecked = function() {
    	// your NoChecked logic here
    };
    
    $(document).ready(function(){
      $('#4').on('click', function(){
      	  // `.prop('checked', true)` will check the checkbox.
          // Triggering click will immediately uncheck the checkbox 
          // (simulating a user click).
          // $('#1').prop('checked', true).trigger('click');
          // $('#2').prop('checked', true).trigger('click');
          
          $('#1').prop('checked', true);
          $('#2').prop('checked', true);
          onYesChecked();
          onNoChecked();
      });
    
      $('#1').on('click', onYesChecked);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label>
      <input id="1" type="checkbox" value="">Yes
    </label>
    <br><br>
    <label>
      <input id="2" type="checkbox" value="">NO
    </label>
    <br><br>
    <label>
      <input id="3" type="text" value="Hello World">Yes
    </label>
    <br><br>
    <input id="4" type="button" value="Submit"/>