How to make a radio button unchecked by clicking it?

Student picture Student · Jun 4, 2012 · Viewed 276.4k times · Source

Unlike check boxes, it is impossible for the user to deselect radio buttons once they are clicked. Is there any way so that they can be toggled programmatically using Javascript? This would be preferably without using jQuery.

Answer

Teneff picture Teneff · Jun 4, 2012

You can set HTML object's property checked to false like this:

document.getElementById('desiredInput').checked = false;

Example: Hold down Ctrl ( on mac) key to uncheck.

var radios = document.getElementsByTagName('input');
for(i=0; i<radios.length; i++ ) {
    radios[i].onclick = function(e) {
        if(e.ctrlKey || e.metaKey) {
            this.checked = false;
        }
    }
}
<input type="radio" name="test" value="1" />
<input type="radio" name="test" value="2" checked="checked" />
<input type="radio" name="test" value="3" />

jQuery example