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.
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.
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.
If you're on a radio or checkbox choice, just hit spacebar to select or unselect that active option.
You can set HTML object's property checked
to false
like this:
document.getElementById('desiredInput').checked = false;
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" />
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With