Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a radio button unchecked by clicking it?

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.

like image 767
Student Avatar asked Jun 04 '12 06:06

Student


People also ask

How do you uncheck a radio button React?

To uncheck radio buttons in React, we can set the checked prop of the radio button to false . We have the checked state that we use to set the checked prop of each radio button.

Why can't I uncheck my radio button?

The reason why it's impossible to deselect HTML “radio” inputs. Radio buttons are not supposed to be left blank. They can be left blank only if you do not want to use default values. This allows you to do things like force the user to fill in the form and not assume anything by default if it is required.

How do I uncheck a radio button on my keyboard?

If you're on a radio or checkbox choice, just hit spacebar to select or unselect that active option.


2 Answers

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

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

Examples

Plain JavaScript:

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:

$('input').click(function(e){     if (e.ctrlKey || e.metaKey) {         $(this).prop('checked', false);     } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="radio" name="test" value="1" /> <input type="radio" name="test" value="2" checked="checked" /> <input type="radio" name="test" value="3" />

Hold down Ctrl ( on mac) key to uncheck.

like image 182
Teneff Avatar answered Sep 28 '22 02:09

Teneff


Radio buttons are meant to be used in groups, as defined by their sharing the same name attribute. Then clicking on one of them deselects the currently selected one. To allow the user to cancel a “real” selection he has made, you can include a radio button that corresponds to a null choice, like “Do not know” or “No answer”.

If you want a single button that can be checked or unchecked, use a checkbox.

It is possible (but normally not relevant) to uncheck a radio button in JavaScript, simply by setting its checked property to false, e.g.

<input type=radio name=foo id=foo value=var> <input type=button value="Uncheck" onclick= "document.getElementById('foo').checked = false"> 
like image 37
Jukka K. Korpela Avatar answered Sep 28 '22 01:09

Jukka K. Korpela