Javascript 如何通过单击取消选中单选按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10876953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a radio button unchecked by clicking it?
提问by Student
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.
与复选框不同,一旦单击单选按钮,用户就无法取消选择它们。有什么办法可以使用Javascript以编程方式切换它们吗?这最好不使用 jQuery。
回答by Teneff
You can set HTML object's property checked
to false
like this:
您可以HTML对象的属性设置checked
,以false
这样的:
document.getElementById('desiredInput').checked = false;
PS: Hold down Ctrlkey to uncheck.
PS:按住Ctrl键取消勾选。
回答by Jukka K. Korpela
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”.
单选按钮旨在按组使用,因为它们共享相同的name
属性。然后单击其中之一取消选择当前选定的一个。为了允许用户取消他所做的“真实”选择,您可以包含一个与空选择相对应的单选按钮,例如“不知道”或“没有答案”。
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.
可以(但通常不相关)取消选中 JavaScript 中的单选按钮,只需将其checked
属性设置为 false,例如
<input type=radio name=foo id=foo value=var>
<input type=button value="Uncheck" onclick=
"document.getElementById('foo').checked = false">
回答by Shmili Breuer
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 )
这是我的答案(虽然我是用 jQuery 制作的,但仅用于选择器并添加和删除类,因此您可以轻松地用纯 JS 选择器和纯 JS 添加属性替换它)
<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");
};
})
回答by Shmili Breuer
Wrapped up in a plugin
包裹在一个插件中
Limitations:
限制:
- Require form element
- 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>
回答by user3716078
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.
由于单选按钮主要在组中使用,因此getElementsByName( ' ' );
在脚本标签中更容易抓取它们。这将返回一个数组,在每个数组子级上放置一个事件侦听器并设置检查状态。看看这个样本。
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.
回答by me_
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...
虽然它是在 javascript 方面被问到的,但 jquery 的适应是微不足道的......使用这种方法你可以检查“空”值并传递它......
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">
回答by Pedro San??o
Old question but people keep coming from Google here and OP asked preferably without jQuery, so here is my shot.
老问题,但人们一直从谷歌过来,OP 最好在没有 jQuery 的情况下询问,所以这是我的镜头。
Should works even on IE 9
应该适用于 IE 9
// iterate using Array method for compatibility
Array.prototype.forEach.call(document.querySelectorAll('[type=radio]'), function(radio) {
radio.addEventListener('click', function(){
var self = this;
// get all elements with same name but itself and mark them unchecked
Array.prototype.filter.call(document.getElementsByName(this.name), function(filterEl) {
return self !== filterEl;
}).forEach(function(otherEl) {
delete otherEl.dataset.check
})
// set state based on previous one
if (this.dataset.hasOwnProperty('check')) {
this.checked = false
delete this.dataset.check
} else {
this.dataset.check = ''
}
}, false)
})
<label><input type="radio" name="foo" value="1"/>foo = 1</label><br/>
<label><input type="radio" name="foo" value="2"/>foo = 2</label><br/>
<label><input type="radio" name="foo" value="3"/>foo = 3</label><br/>
<br/>
<label><input type="radio" name="bar" value="1"/>bar = 1</label><br/>
<label><input type="radio" name="bar" value="2"/>bar = 2</label><br/>
<label><input type="radio" name="bar" value="3"/>bar = 3</label><br/>
回答by my_stk_oflw_account
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);
})
回答by HaLeiVi
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.
让用户 Control+click 几乎与让他们通过控制台取消选中它一样好。抓住 mousedown 太早,而 onclick 太晚了。
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>
回答by A2D
Extending user3716078's answer to allow multiple independent radio button groups and a neater way of assigning event listeners to multiple elements...
扩展 user3716078 的答案以允许多个独立的单选按钮组以及将事件侦听器分配给多个元素的更简洁的方式...
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);
});
}