1

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.

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, Tim! Do you know how to put the reset function to the "None of the above" checkbox?
Sure, I have updated my answer.
Thanks, Tim. I will look into these!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.