Skip to content
Advertisement

Need help on Checkbox onclick jquery

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on “none of the above” button.

<html>
  <body>

    <form id="diagnosedForm">
      <div>
      <input type="checkbox" value="1"/>1
      <br/>
      <input type="checkbox" value="2"/>2
      <br/>
      <input type="checkbox" value="3"/>3
      <br/>
    </form><br/>
    <input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above

    <script src="script.js">
    </script>

  </body>
</html>

 function enableDisableAll(e) {
   var own = e;
   var form = document.getElementById("diagnosedForm");
   var elements = form.elements;

 for (var i = 0 ; i < elements.length ; i++) {
   if(own !== elements[i] ){
     if(own.checked == true){
       elements[i].disabled = true;
       elements[i].checked = false;
     }else{ 
       elements[i].disabled = false;  
       }
     }
   }
 }

this will be the output

and the last checkbox will make it read-only

I want the same result but not putting onclick on the html file, instead using jquery to work it out.

Advertisement

Answer

You can assign an id to “none of the above” checkbox and then in your script.js you can do something like this:

// script.js

// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)

function enableDisableAll() {
  // Find all input elements inside "diagnosedForm"
  const elements = $('#diagnosedForm input')

  // Map thru inputs and toggle enable/disable state
  elements.map((_, el) => {
    $(el).prop('checked', false) // Reset checkboxes
    $(el).prop('disabled', (i, v) => !v)
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>

<body>

  <form id="diagnosedForm">
    <div>
      <input type="checkbox" value="1" />1
      <br/>
      <input type="checkbox" value="2" />2
      <br/>
      <input type="checkbox" value="3" />3
      <br/>
    </div>
  </form>
  <br/>
  <input id="toggle" type="checkbox" value="" /> None of the above
  
</body>

</html>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement