如何通过单击取消选中单选按钮?
与复选框不同,用户无法在单击单选按钮后取消选择它们.有什么方法可以使用 Javascript 以编程方式切换它们?最好不要使用 jQuery.
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.
推荐答案
你可以像这样设置 HTML 对象的属性 checked
为 false
:
You can set HTML object's property checked
to false
like this:
document.getElementById('desiredInput').checked = false;
示例
纯 JavaScript
:
Examples
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" />
$('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" />
相关文章