Home » Javascript » If radio button is unchecked, automatically check another radio button with JavaScript

If radio button is unchecked, automatically check another radio button with JavaScript

Posted by: admin August 12, 2018 Leave a comment

Questions:

I’m making a form with 2 radio buttons inside of the form. When the page with the form loads, the radio button with ‘None’ is automatically checked. I also wanted to be able to ‘uncheck’ the radio buttons, kinda like the functionality of a checkbox. I managed to do this. Now I have one more thing to do, which is the following one:

If the radio button with value ‘Unconfirmed’ is unchecked, the radio button with the value ‘None’ needs to be automatically checked again. I know that this would be easy with checkboxes, but the users can only check one of the 2 options.

My current code:

var allElems = document.getElementsByTagName('input');
for (i = 0; i < allElems.length; i++) {
  if (allElems[i].type == 'radio' && allElems[i].value == 'none') {
    allElems[i].checked = true;
  }
}

$('form :radio').attr('data-ischecked', function() {
  return this.checked;
}); //set initial status in data-ischecked attribute

$('form').on('click', ':radio', function() {
  var status = $(this).data('ischecked'); //get status
  status && $(this).prop("checked", false); //uncheck if checked
  $(this).data('ischecked', !status); //toggle status
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <label for="none">None</label>
  <input type="radio" id="none" name="myradios" value="none" />
  <label for="unconfirmed">Unconfirmed</label>
  <input type="radio" id="unconfirmed" name="myradios" value="unconfirmed" />
</form>
Answers: