0

I would like to have the possibility with javascript to deselect checkbox "demo2" when I deselect checkbox "demo1". only deselect

<input type="checkbox" name="demo1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" name="demo2" value="Car">
<label for="vehicle2"> I have a car</label><br>
4
  • What is "demo1"? Commented Jan 15, 2021 at 14:18
  • Please provide a code snippet of your work so far so that we can help you modify it. Basically you can accomplish this with a change listener on demo1 and a check to see its status via .checked Commented Jan 15, 2021 at 14:26
  • Can you not use radio buttons? They are intented for this type of use, with only one option selected at a time. It will work OOTB Commented Jan 15, 2021 at 14:37
  • Use radio buttons, as @jeroen kindly suggested. Don't try to reinvent the way basic form controls are meant to be used. Commented Jan 15, 2021 at 14:41

1 Answer 1

1

I gues you just want to have "radio" like behaviour. You can see below how it can be done with pure JS.

<html>
<body>
<script>
function switcher(obj) {
   if(obj.checked == true) {
      document.getElementsByName('demo2')[0].checked = false;
      document.getElementsByName('demo1')[0].checked = false;
      obj.checked= true
   }
}
</script>

<input type="checkbox" name="demo1" value="Bike" onclick="switcher(this)">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" name="demo2" value="Car" onclick="switcher(this)">
<label for="vehicle2"> I have a car</label><br>

</body>
</html>

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

2 Comments

Thanks for the reply but it is not what I wanted, I apologize for having explained me wrong. demo1 and demo 2 can also be selected both, but demo2 can only be selected if demo1 is selected, and when demo1 is de-selected also demo2 must be deselected
Ok, this is still not far off. You can create another method and apply the checks as wanted.

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.