Three ways to deselect radio

  • 2020-03-30 03:56:51
  • OfStack

This article provides three ways to uncheck radio, with the following code examples:

This article relies on jQuery, the first of which is implemented using jQuery, the second is implemented using jQuery, and the third is implemented using JS and DOM.


<!DOCTYPE HTML> 
<html> 
<head> 
<title> Three ways to deselect a radio button </title> 
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"> 
</script> 
<script type="text/javascript"> 
$(function(){ 
// 
var $browsers = $("input[name=browser]"); 
var $cancel = $("#cancel"); 
var $byhide = $("#byhide"); 
var $remove = $("#remove"); 
// 
$cancel.click(function(e){ 
//Remove attributes, either way
//$browsers.removeAttr("checked"); 
$browsers.attr("checked",false); 
}); 
// 
$byhide.click(function(e){ 
//Switch to a hidden field, either way
//$("#hidebrowser").attr("checked",true); 
$("#hidebrowser").attr("checked","checked"); 
}); 
// 
$remove.click(function(e){ 
//Go directly to the DOM element and remove the attribute
//If you don't use jQuery, you can port this approach
var checkedbrowser=document.getElementsByName("browser"); 
 
// 
var len = checkedbrowser.length; 
var i = 0; 
for(; i < len; i++){ 
//You must first assign false and then remove the property
checkedbrowser[i].checked = false; 
//You can do this without removing the property
//checkedbrowser[i].removeAttribute("checked"); 
} 

}); 
}); 
</script> 
</head> 
<body> 
<p> Which browser do you prefer? </p> 

<form> 
<input style="display:none;" id="hidebrowser" type="radio" name="browser" value=""> 
<input type="radio" name="browser" value="Internet Explorer">Internet Explorer<br /> 
<input type="radio" name="browser" value="Firefox">Firefox<br /> 
<input type="radio" name="browser" value="Netscape">Netscape<br /> 
<input type="radio" name="browser" value="Opera">Opera<br /> 
<br /> 
<input type="button" id="cancel" value=" Deselect mode 1" size="20"> 
<input type="button" id="byhide" value=" Deselect mode 2" size="20"> 
<input type="button" id="remove" value=" Deselect mode 3" size="20"> 
</form> 

</body> 
</html>

Related articles: