How to Uncheck a Radio Button in JavaScript

Radio buttons are widely used in web development for selecting single options from multiple options.

Sometimes, we need to uncheck a radio button after the user has selected it.

In this Javascript tutorial, we will learn how to uncheck a radio button using JavaScript.


Understanding Radio Buttons

A radio button is a type of graphical user interface element that allows the user to choose only one option from a set of predefined options.

Radio buttons are used in forms, surveys, and quizzes to collect user data.

Radio buttons are represented as small circular buttons with a dot in the center.

When a radio button is selected, the dot is filled with a different color, indicating that it is selected.

Radio buttons are usually grouped together, and only one button in the group can be selected at a time.

Unchecking a Radio Button in JavaScript

The process of unchecking a radio button in JavaScript involves accessing the radio button element, setting its “checked” property to false, and triggering a change event.

Let’s take a look at the code.

<input type="radio" id="radio1" name="group1" value="option1" checked>
<label for="radio1">Option 1</label><br>

<input type="radio" id="radio2" name="group1" value="option2">
<label for="radio2">Option 2</label><br>

<button id="uncheckButton">Uncheck Radio Button</button>

<script>
  const radioButton = document.querySelector('input[name="group1"]:checked');
  const uncheckButton = document.querySelector('#uncheckButton');

  uncheckButton.addEventListener('click', function() {
    radioButton.checked = false;
    radioButton.dispatchEvent(new Event('change'));
  });
</script>

In this code example, we have two radio buttons with the same name “group1.”

This means that they are part of the same group, and only one of them can be selected at a time.

We have also added a button with the ID “uncheckButton” that, when clicked, will uncheck the selected radio button.

First, we use the querySelector method to select the checked radio button in the group.

We then attach a click event listener to the uncheckButton element.

When the button is clicked, the checked property of the radioButton is set to false, which unchecks the radio button.

Finally, we dispatch a change event on the radio button to trigger any event handlers that may be listening for changes in the radio button’s state.


Conclusion

In this Javascript tutorial, we learned how to uncheck a radio button in JavaScript.

By accessing the radio button element, setting its “checked” property to false, and triggering a change event, we can uncheck a selected radio button.

This can be useful in various scenarios where you need to allow the user to change their selection.