与复选框不同,单选按钮一旦被单击,用户就不可能取消选择它们。有没有办法可以使用Javascript以编程方式切换它们?这最好不使用jQuery。
发布于 2012-06-04 06:13:51
单选按钮旨在按组使用,因为它们共享相同的name
属性。然后,单击其中一个将取消选择当前选定的一个。要允许用户取消他所做的“真实”选择,您可以包括一个对应于空选择的单选按钮,如“不知道”或“无回答”。
如果您想要一个可以选中或取消选中的按钮,请使用复选框。
可以(但通常不相关)在JavaScript中取消选中某个单选按钮,只需将其checked
属性设置为false即可,例如
<input type=radio name=foo id=foo value=var>
<input type=button value="Uncheck" onclick=
"document.getElementById('foo').checked = false">
发布于 2016-01-13 22:57:45
这就是我的答案(虽然我是用jQuery实现的,但仅用于选择元素以及添加和删除类,因此您可以轻松地将其替换为纯JS选择器&纯JS add属性)。
<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");
};
})
发布于 2016-05-09 04:31:02
封装在一个插件中
限制:
更改单选按钮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>
https://stackoverflow.com/questions/10876953
复制