Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear radio button in Javascript?

I have a radio button named "Choose" with the options yes and no. If I select any one of the options and click the button labeled "clear", I need to clear the selected option, using javascript. How can I accomplish that?

like image 310
i2ijeya Avatar asked Mar 31 '10 15:03

i2ijeya


People also ask

How do I uncheck a radio in JavaScript?

To set a radio button to checked/unchecked, select the element and set its checked property to true or false , e.g. myRadio. checked = true .

How do I reset the radio button in React?

To reset radio buttons in React on click of a Reset button, we set empty string '' or null value to the radio state gender on click of the button. Pass the resetRadioState function to the onClick event handler.


6 Answers

You don't need to have unique id for the elements, you can access them by their name attribute:

If you're using name="Choose", then:

  • With jQuery it is as simple as:

    $('input[name=Choose]').attr('checked',false);
    
  • or in pure JavaScript:

       var ele = document.getElementsByName("Choose");
       for(var i=0;i<ele.length;i++)
          ele[i].checked = false;
    

    Demo for JavaScript

like image 55
NVRAM Avatar answered Oct 05 '22 23:10

NVRAM


If you do not intend to use jQuery, you can use simple javascript like this

document.querySelector('input[name="Choose"]:checked').checked = false;

Only benefit with this is you don't have to use loops for two radio buttons

like image 44
shriroop_ Avatar answered Oct 06 '22 00:10

shriroop_


This should work. Make sure each button has a unique ID. (Replace Choose_Yes and Choose_No with the IDs of your two radio buttons)

document.getElementById("Choose_Yes").checked = false;
document.getElementById("Choose_No").checked = false;

An example of how the radio buttons should be named:

<input type="radio" name="Choose" id="Choose_Yes" value="1" /> Yes
<input type="radio" name="Choose" id="Choose_No" value="2" /> No
like image 43
Shawn Steward Avatar answered Oct 05 '22 22:10

Shawn Steward


An ES6 approach to clearing a group of radio buttons:

    Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
like image 36
wLc Avatar answered Oct 06 '22 00:10

wLc


Wouldn't a better alternative be to just add a third button ("neither") that will give the same result as none selected?

like image 35
Jasper De Bruijn Avatar answered Oct 05 '22 22:10

Jasper De Bruijn


In my case this got the job done:

const chbx = document.getElementsByName("input_name");

for(let i=0; i < chbx.length; i++) {
    chbx[i].checked = false;
}
like image 37
Avag Sargsyan Avatar answered Oct 05 '22 22:10

Avag Sargsyan