Home » Html » How to make a radio button unchecked by clicking it?

How to make a radio button unchecked by clicking it?

Posted by: admin December 10, 2017 Leave a comment

Questions:

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.

Answers:

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

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

JavaScript example

jQuery example

PS: Hold down Ctrl key to uncheck.

Questions:
Answers:

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">

Questions:
Answers:

As radio button mostly used in group, its a lot easier to grab them by getElementsByName( ' ' ); in your script tag. This will return an array, put an event listener on each array child and set the check state. Look at this sample.

var myRadios = document.getElementsByName('subscribe');
var setCheck;
var x = 0;
for(x = 0; x < myRadios.length; x++){

    myRadios[x].onclick = function(){
        if(setCheck != this){
             setCheck = this;
        }else{
            this.checked = false;
            setCheck = null;
    }
    };

}

This guide explain how the code works with a visual demonstration.

Questions:
Answers:

This is my answer (though I made it with jQuery but only for selectors and add and remove a class, so you can easily replace it with pure JS selectors & pure JS add attribute )

<input type='radio' name='radioBtn'>
<input type='radio' name='radioBtn'>
<input type='radio' name='radioBtn'>

$(document).on("click", "input[name='radioBtn']", function(){
    thisRadio = $(this);
    if (thisRadio.hasClass("imChecked")) {
        thisRadio.removeClass("imChecked");
        thisRadio.prop('checked', false);
    } else { 
        thisRadio.prop('checked', true);
        thisRadio.addClass("imChecked");
    };
})

Questions:
Answers:

Wrapped up in a plugin

Limitations:

  1. Require form element
  2. Must trigger click event when changing radio button programmatically
(function($) {
  $.fn.uncheckableRadio = function() {
    var $root = this;
    $root.each(function() {
      var $radio = $(this);
      if ($radio.prop('checked')) {
        $radio.data('checked', true);
      } else {
        $radio.data('checked', false);
      }
        
      $radio.click(function() {
        var $this = $(this);
        if ($this.data('checked')) {
          $this.prop('checked', false);
          $this.data('checked', false);
          $this.trigger('change');
        } else {
          $this.data('checked', true);
          $this.closest('form').find('[name="' + $this.prop('name') + '"]').not($this).data('checked', false);
        }
      });
    });
    return $root;
  };
}(jQuery));

$('[type=radio]').uncheckableRadio();
$('button').click(function() {
  $('[value=V2]').prop('checked', true).trigger('change').trigger('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <label><input name="myRadio" type="radio" value="V1" /> R1</label>
  <label><input name="myRadio" type="radio" value="V2" /> R2</label>
  <label><input name="myRadio" type="radio" value="V3" /> R3</label>
  <button type="button">Change R2</button>
</form>

Questions:
Answers:

That’s what I came to:

function uncheck_radio_before_click(radio) {
    if(radio.prop('checked'))
        radio.one('click', function(){ radio.prop('checked', false); } );
}
$('body').on('mouseup', 'input[type="radio"]', function(){
    var radio=$(this);
    uncheck_radio_before_click(radio);
})
$('body').on('mouseup', 'label', function(){
    var label=$(this);
    var radio;
    if(label.attr('for'))
        radio=$('#'+label.attr('for')).filter('input[type="radio"]');
    else
        radio=label.children('input[type="radio"]');
    if(radio.length)
        uncheck_radio_before_click(radio);
})

http://jsfiddle.net/24vft2of/2/

Questions:
Answers:

You could use the checked property of a radio button to uncheck it.

Something like this:

<script>
 function uncheck()
 {
  document.getElementById('myRadio').checked = false;        
 }
 function check()
 {
  document.getElementById('myRadio').checked = true;        
 }
</script>
<input id="myRadio" type="radio" checked="checked"/>
<button onclick="uncheck();">Uncheck</button>
<button onclick="check();">Check</button>

​See it in action here: http://jsfiddle.net/wgYNa/

Questions:
Answers:

The full code will look something like this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<input name="radio" type="radio" id="myRadio" value="myRadio" checked="checked"     onclick="setRadio(this)" />
<label for="myRadio"></label>


<script language="javascript">
function setRadio(obj) 
{
    obj.checked = false;
}
</script>
</body>
</html>

Questions:
Answers:

Here’s an example of where it is arguably appropriate to uncheck radio buttons other than by making a new selection. I have a dictionary whose entries can be selected using a variety of indices. Which index to use is selected by means of a set of radio buttons. However, there is also a “random entry” button that the user can use if he or she just wants to browse. Leaving an index in place when the entry has been selected by means of the random entry button would be misleading, so when this button is pressed, I uncheck all of the index selection radio buttons and replace the contents of the index frame with an empty page.

Questions:
Answers:

Extending user3716078’s answer to allow multiple independent radio button groups and a neater way of assigning event listeners to multiple elements…

window.onload = function() {

    var acc_checked=[];

    [].slice.call(document.querySelectorAll('.accordion input[type="radio"]')).forEach(function(el,i){
        /**
         * i represents the integer value of where we are in the loop
         * el represents the element in question in the current loop
         */
        el.addEventListener('click', function(e){

            if(acc_checked[this.name] != this) {
                acc_checked[this.name] = this;
            } else {
                this.checked = false;
                acc_checked[this.name] = null;
            }

        }, false);

    });

}

Questions:
Answers:

I came here because I had the same issue. I wanted to present the options to the user while leaving the option of remaining empty. Although this is possible to explicitly code using checkboxes that would complicate the back end.

Having the user Control+click is almost as good as having them uncheck it through the console. Catching the mousedown is to early and onclick is too late.

Well, at last here is a solution! Just put these few lines once on the page and you have it made for all radio buttons on the page. You can even fiddle with the selector to customize it.

window.onload = function(){
document.querySelectorAll("INPUT[type='radio']").forEach(function(rd){rd.addEventListener("mousedown",
	function(){
		if (this.checked) {this.onclick=function(){this.checked=false}} else{this.onclick=null}
	})})}
<input type=radio name=unchecksample> Number One<br>
<input type=radio name=unchecksample> Number Two<br>
<input type=radio name=unchecksample> Number Three<br>
<input type=radio name=unchecksample> Number Four<br>
<input type=radio name=unchecksample> Number Five<br>

Questions:
Answers:

while it was asked in terms of javascript, the adaption from jquery is trivial… with this method you can check for the “null” value and pass it…

var checked_val = "null";
$(".no_option").on("click", function(){
  if($(this).val() == checked_val){
  	$('input[name=group][value=null]').prop("checked",true);
    checked_val = "null";
  }else{
  	checked_val = $(this).val();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="group" class="no_option" value="0">option 0<br>
<input type="radio" name="group" class="no_option" value="1">option 1<br>
<input type="radio" name="group" class="no_option" value="2">option 2<br>
<input type="radio" name="group" class="no_option" value="3">option 3<br>
<input type="radio" name="group" class="no_option" value="4">option 4<br>
<input type="radio" name="group" class="no_option" value="5">option 5<br>
<input type="radio" name="group" class="no_option" value="6">option 6<br>
<input type="radio" name="group" class="no_option" value="null" style="display:none">

Leave a Reply

Your email address will not be published. Required fields are marked *