javascript – uncheck checked radio button-ThrowExceptions

Exception or error:
var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
  radios[i].onclick = function () {
    if (this.checked) {
      this.checked = false;
    }
  }
}
<div id = "container">
  <input type = "radio"  name = "x"> A
  <br>
  <input type = "radio"  name = "x"> B
</div>

what i want is to check one of the radios and if i pressed the checked radio again to uncheck it but it does not check in first place too

how to uncheck a checked radio after it was checked and how to even tell that it is checked or in empty state

How to solve:

I will suggest that you use attribute to control the checked status.

var x = document.getElementsByName('x');
x.forEach(function(e) {
  e.addEventListener('click', function(ev) {
    // set checked by data-checked attribute
    if (e.getAttribute('data-checked') == 'true') {
      e.checked = false;
      e.setAttribute('data-checked', 'false');
    } else {
      e.checked = true;
      e.setAttribute('data-checked', 'true');
    }
    // update attribute of all radios
    x.forEach(function(e2) {
      e2.setAttribute('data-checked', e2.checked);
    });
  });
});
<input type="radio" name="x" data-checked="false"> A<br>
<input type="radio" name="x" data-checked="false"> B<br>
<input type="radio" name="x" data-checked="false"> C<br>

###

Using your current JavaScript code, the moment you click it, it will be checked first before reading the JavaScript code, thus it will appear to be unchecked always. With my suggestions (it can’t be helped sorry) use something like this:

var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
  radios[i].onmousedown = function () {
    if (this.checked) {
      this.checked = false;
      this.onchange = function () {
        this.checked = false;
      }
    }
    else  {
      this.checked = true;
      this.onchange = function () {
        this.checked = true;
      }
    }

  }
}
<div id = "container">
  <input type = "radio"  name = "x"> A
  <br>
  <input type = "radio"  name = "x"> B
</div>

Since I can’t question you why you can’t use checkbox instead, I had to do this. It works for me anyway

###

Use the following code. This is the whole code, try using it:

 <!DOCTYPE html>
<html>
<head>
  <title></title>

</head>
<body >
  <div id = "container">
    <input type = "radio"  name = "x"> A
    <br>
    <input type = "radio"  name = "x"> B
  </div>

</body>
<script type="text/javascript">

var radios = document.getElementsByTagName('input');
for (i = 0; i < radios.length; i++) {
  radios[i].onclick = function () {
    console.log("==>" , this.checked);
    if (this.checked == false) {
      this.checked = true;
    }else{
      this.checked = true;
    }
  }
}
</script>

</html>

Leave a Reply

Your email address will not be published. Required fields are marked *