如何通过单击单选按钮使其取消选中
How to make a radio button unchecked by clicking it?
与复选框不同,用户一旦单击单选按钮就无法取消选择。 有什么方法可以使用Javascript以编程方式切换它们? 这最好不使用jQuery。
您可以将 HTML 对象的属性checked
设置为false
,如下所示:
document.getElementById('desiredInput').checked = false;
<小时 />例子
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" />
jQuery
:
$('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" />
按住 按Ctrl(⌘ 在 Mac 上)键取消选中。
单选按钮旨在用于组,由它们共享相同的name
属性定义。然后单击其中一个取消选择当前选定的一个。要允许用户取消他所做的"真实"选择,您可以包含一个对应于空选项的单选按钮,例如"不知道"或"无答案"。
或取消选中的单个按钮,请使用复选框。
可以(但通常不相关)取消选中 JavaScript 中的单选按钮,只需将其 checked
属性设置为 false,例如
<input type=radio name=foo id=foo value=var>
<input type=button value="Uncheck" onclick=
"document.getElementById('foo').checked = false">
的答案(虽然我用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");
};
})
选中无线电如何(不)工作
您不能通过 if(this.checked) this.checked = false
轻松实现取消选中,(如果您真的想,请参阅最后的黑客方式),因为事件按以下顺序触发:
-
mousedown
或keydown
-
mouseup
或keyup
- 如果未选中,请立即设置选中的属性
-
click
-
input
(仅当状态更改时) -
change
(仅当状态更改时)
现在在什么情况下执行上述取消选中?
-
mouseup
或mousedown
:然后在步骤 3 中,该值被设置回 true 并且更改和输入事件甚至不会触发,因为当它们在序列中被调用时状态没有改变 - 所以你不能在这里取消选中它 -
click
:那么状态总是假的,输入和更改也不会触发 - 所以你不能检查它 -
input
或change
:当状态未更改且单击所选元素不会更改状态时,它不会触发 - 因此您在这里无法执行任何有用的操作
天真的方式
正如您可以从上面的序列中了解到的那样,方法是:
- 在
mouseup
中读取以前的状态 - 将
click
中的状态设置为对先前状态的否定
如果要将以前的状态存储在 data 属性中,请记住它保存为字符串,而选中的属性是布尔值。因此,您可以像以下方式实现它:
radio.onmouseup = function() { this.dataset.checked = this.checked? 1 : ""; }
radio.onclick = function() { this.checked = !this.dataset.checked; }
它似乎有效,但由于以下原因,您不应该这样做:
- 用户可以
mousedown
其他地方,然后将鼠标悬停在单选按钮上方,然后mouseup
:在这种情况下,鼠标向上触发并且单击不 - 用户可以使用 Tab 键聚焦单选按钮组,然后使用箭头进行更改:鼠标向上不触发,单击"执行
正确的方式
还有另一个问题:动态添加的单选按钮。有两种方法:
-
element.appendChild(radio)
- 如果在事件中的所有无线电上启用取消选择DOMContentLoaded
则此动态添加的无线电不受影响 -
element.innerHTML+= '<input type="radio">'
- 有效地替换元素的 HTML 内容并在其中重新创建 DOM - 因此丢弃所有事件侦听器
为了解决(2),我建议点击内容属性。请注意,element.onclick = fn
和element.setAttribute("onclick", "fn()")
是两个不同的东西。另请注意,每次用户激活无线电时都会触发onclick
,无论他使用什么接口。
另一个问题:如果启用取消选择,则还应启用按空格键切换以模仿复选框行为。以下代码解决了所有提到的问题:
function deselectableRadios(rootElement) {
if(!rootElement) rootElement = document;
if(!window.radioChecked) window.radioChecked = {};
window.radioClick = function(e) {
const obj = e.target, name = obj.name || "unnamed";
if(e.keyCode) return obj.checked = e.keyCode!=32;
obj.checked = window.radioChecked[name] != obj;
window.radioChecked[name] = obj.checked ? obj : null;
}
rootElement.querySelectorAll("input[type='radio']").forEach( radio => {
radio.setAttribute("onclick", "radioClick(event)");
radio.setAttribute("onkeyup", "radioClick(event)");
});
}
deselectableRadios();
<label><input type="radio" name="tag1">one</label>
<label><input type="radio" name="tag1">two</label>
<label><input type="radio" name="tag1">three</label>
<br><br>
<label><input type="radio" name="tag2">one</label>
<label><input type="radio" name="tag2">two</label>
<label><input type="radio" name="tag2">three</label>
现在,您可以随时动态添加内容来调用deselectableRadios()
并且多次在无线电上调用它不会破坏它。您还可以指定仅更新 HTML DOM 子树并使您的 Web 更快的rootElement
。如果你不喜欢全局状态,你可以使用黑客的方式:
黑客的方式
关键是在设置选中的属性后mouseup
调用它setTimeout
滥用:
function deselectable() {
setTimeout(checked => this.checked = !checked, 0, this.checked);
}
现在,您可以将任何单选按钮设为可取消选择:
radio.onmouseup = deselectable;
但是这个简单的单行代码仅适用于单击,并不能解决上述问题。
被遗弃的未来
可取消选择的无线电基本上是复选框,其中只能选中组中的一个。有一个有希望的直接希望将其编码为
<input type="checkbox" name="foo" style="appearance: radio">
然而,radio
值现在被定义为兼容自动类型,它被视为auto
,即没有视觉变化。看来以后这里不会有任何进展。
包含在插件中
局限性:
- 需要表单元素
- 以编程方式更改单选按钮时必须触发单击事件
(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>
由于单选按钮主要用于组中,因此通过在脚本标签中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;
}
};
}
本指南通过可视化演示说明代码的工作原理。
虽然有人问它关于JavaScript,但jquery的改编是微不足道的...... 使用此方法,您可以检查"null"值并传递它...
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">
老问题,但人们不断来自谷歌,OP最好在没有jQuery的情况下问,所以这是我的镜头。
即使在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/>
我来这里是因为我遇到了同样的问题。我想向用户显示选项,同时保留为空的选项。尽管可以使用复选框显式编码,这将使后端复杂化。
让用户 Control+单击几乎和让他们通过控制台取消选中它一样好。抓住鼠标按下是早点,点击为时已晚。
好吧,终于有一个解决方案了!只需将这几行放在页面上一次,您就可以为页面上的所有单选按钮制作它。您甚至可以摆弄选择器来自定义它。
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>
这就是我得出的结论:
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/
在单选按钮对象创建代码中包括以下三行:
obj.check2 = false; // add 'check2', a user-defined object property
obj.onmouseup = function() { this.check2 = this.checked };
obj.onclick = function() { this.checked = !this.check2 };
纯 JavaScript 中的完整示例:
box.onmouseup = function() {
var temp = this.children[0];
if (temp.checked) {
setTimeout(function() {
temp.checked = false;
}, 0);
}
}
<label id='box' style='margin-right: 1em;'>
<input type='radio' name='chk_préf_méd_perso' value='valeur'>
libellé
</label>
惊讶没有人发布这个不使用任何JavaScript的"巧妙技巧"版本,它只使用CSS。
#radio1 {
display: none;
}
#wrapper {
/* NOTE: This wrapper div is not needed provided you can position the label for #radio1 on top of #radio2 using some other technique. */
position: relative;
}
#radio1:not(:checked) ~ * label[for="radio1"] {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#radio1:checked ~ * label[for="radio1"] {
display: none;
}
/* Non-essential styles: */
label[for],
label:not([for="radio1"]) {
cursor: pointer;
border-radius: 7px;
}
label[for]:hover + label,
label:not([for="radio1"]):hover {
background-color: #ccc;
}
<input type="radio" name="group1" id="radio1" checked="checked" />
<p>Look mum, <strong>no JavaScript!</strong></p>
<div id="wrapper">
<label for="radio1"></label>
<label>
<input type="radio" name="group1" id="radio2" />
You can toggle me on and off!
</label>
</div>
<小时 />解释:
-
#radio1
(<input type="radio" id="radio2" />
)总是隐藏的。 - 使用CSS的
:checked
和:not(:checked)
伪类选择器与同级选择器(+
和~
)允许其他元素的样式受到影响,这取决于是否选中了<input type="checkbox" />
或<input type="radio" />
。- 因此,当
#radio1
未选中时(或选中#radio2
时),这会导致<label>
覆盖在#radio2
的顶部并且该标签已for="radio1"
,因此单击它将导致#radio1
被选中,而不是#radio2
。 - 重要警告:CSS 的同级选择器规则仅允许选择器根据其祖先及其祖先早期的兄弟姐妹选择元素。因此,您不能基于元素祖先的任何其他后代来设置元素的样式。
- 当支持 CSS4
- 的
:has()
选择器功能时,此限制将被删除,但截至 2020 年 11 月,只有 PrinceXML 支持:has()
并且由于难以实现,目前看起来:has()
将从 CSS4 中完全删除。
- 的
- 因此,当
此方法可以扩展为支持多个单选按钮:
#uncheckAll {
display: none;
}
#uncheckAll:checked ~ * label[for="uncheckAll"] {
display: none;
}
label {
cursor: pointer;
}
label:not([for]) {
position: relative;
}
label[for="uncheckAll"] {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
input[name="group1"]:not(:checked) + label[for="uncheckAll"] {
display: none;
}
<input type="radio" name="group1" id="uncheckAll" checked="checked" />
<label>
<input type="radio" name="group1" id="radio2" />
<label for="uncheckAll"></label>
You can toggle me on and off!
</label>
<label>
<input type="radio" name="group1" id="radio3" />
<label for="uncheckAll"></label>
And me!
</label>
<label>
<input type="radio" name="group1" id="aragorn" />
<label for="uncheckAll"></label>
And my sword!
</label>
<label>
<input type="radio" name="group1" id="gimli" />
<label for="uncheckAll"></label>
And my axe!
</label>
扩展 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);
});
}
<</div>
div class="answers"> 我将尝试用 3 个单选按钮做一个小答案,您可以稍后添加内容。
const radios = Array.from(document.getElementsByClassName('radio'))
for(let i of radios) {
i.state = false
i.onclick = () => {
i.checked = i.state = !i.state
for(let j of radios)
if(j !== i) j.checked = j.state = false
}
}
<input class="radio" type="radio">X
<input class="radio" type="radio">Y
<input class="radio" type="radio">Z
这适用于单一形式。如果您有多个带有class="radio"的表单,那么一旦单击单选按钮,其他表单就会被禁用。如果这是您想要的,请使用它。<小时 />现在我想在我的 rails 项目上实现这一点,该项目有多个表单(依赖,从数据库中获取),每个表单都有 2 个可见的单选按钮 + 1 个隐藏的单选按钮。
我希望用户选择/取消选择每个表单的单选按钮。在窗体上选择一个按钮不应取消选择另一个窗体上的另一个选定按钮。所以我宁愿这样做:
var radios = Array.from(document.getElementsByClassName('radio'))
for (let i of radios) {
i.state = false
i.onclick = () => {
i.checked = i.state = !i.state
for (let j of radios)
if (j !== i) j.state = false
}
}
<form>
<input class="radio" name="A" type="radio">A
<input class="radio" name="A" type="radio">B
<input class="radio" name="A" type="radio">C
</form>
<form>
<input class="radio" name="A" type="radio">D
<input class="radio" name="A" type="radio">E
<input class="radio" name="A" type="radio">F
</form>
<form>
<input class="radio" name="SOMETHING" type="radio">G
<input class="radio" name="SOMETHING" type="radio">H
<input class="radio" name="SOMETHING" type="radio">I
</form>
您会看到所有表单都具有相同的名称,但它们采用不同的形式,按 3 分组,因此这适用于多个表单。
已经很晚了(现在甚至没有必要),这里有很多解决方案,但我找不到任何针对所问问题的具体内容,或者对于这个简单的场景,其中的代码太多,人们在寻找答案时可以轻松忽略它。
所以在这里,我提出我的解决方案,因为它可能会帮助任何新手。这个想法很简单,只是
- 在我的情况下,在所需的切换上设置相同的类,其"切换"
- 获取鼠标悬停操作切换的当前值
- 反转切换值。
通过这种方式,您可以选择任何切换开关或完全忽略它们,但再次单击已选择的切换开关。您也可以使用给定的代码段对此进行测试。
var val;
$('.toggles').mouseup(function(){
val = this.checked
}).click(function(){
this.checked = val == true ? false : true
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<input class="toggles form-check-input" type="radio" value="true" name="enabled" id="enabled_true">
<label class="form-check-label" for="enabled_true">Enabled</label>
<input class="toggles form-check-input" type="radio" value="false" name="enabled" id="enabled_false">
<label class="form-check-label" for="enabled_false">Disabled</label>
</div>
现代浏览器都认为checked="anything"
是checked="true"
。
的情况下有意义,则可能必须删除该属性,其中一个属性可能与您加载页面的时间有关。
$(this).removeAttr('checked')
如果您希望检查单选按钮是否符合某些条件,这可能会对您有所帮助。您可以简单地删除该属性来实现这一点。
PS:在所有情况下都没有帮助。
这是普通 JS 的方法,将onchange
和onclick
事件组合在一起(onchange
用于检查,而onclick
用于取消选中)。
document.querySelector("input").onchange = function() {
this.onclick = function() {
this.checked = false;
this.onclick = null;
}
};
如果你正在jQuery中寻找解决方案,这里是。它类似于这个
$('input:radio').click(function() {
let name = $(this).attr('name');
let self = $(this);
[].filter.call($(`input[name=${name}]`), function(ele){
return self[0] !== $(ele)[0];
}).forEach(function(otherEle){
$(otherEle).removeAttr('data-check');
});
if($(this).attr('data-check')){
$(this).prop("checked", false);
$(this).removeAttr('data-check');
}else{
$(this).attr("data-check", "1");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input class="radio" name="A" type="radio">A
<input class="radio" name="A" type="radio">B
<input class="radio" name="A" type="radio">C
</form>
<form>
<input class="radio" name="B" type="radio">D
<input class="radio" name="B" type="radio">E
<input class="radio" name="B" type="radio">F
</form>
<form>
<input class="radio" name="C" type="radio">G
<input class="radio" name="C" type="radio">H
<input class="radio" name="C" type="radio">I
</form>
我遇到了这个问题,我的解决方案相当简单,我只是将它们放入复选框中,当一个复选框被切换时,我取消选择了组中的所有其他复选框。
我知道它有点笨拙,并且有很大的O复杂性(虽然n很小),但它有效!(待办事项:为变量考虑更多原始名称)
$(document).ready(function() {
$("input[name=days]").each((_, el) => {
el.addEventListener("click", function () {
$("input[name=days]").each((_, myEl) => {
if (el != myEl) {
myEl.checked = false;
}
});
// Do other stuff
});
});
});
.radio-selector {
display: inline-flex;
flex-wrap: wrap;
vertical-align: top;
justify-content: center;
align-items: center;
margin: 0 auto;
border: 0;
}
.radio-selector input {
position: absolute !important;
clip: rect(0, 0, 0, 0);
}
.radio-selector label {
margin: 0 1rem 1rem 0;
padding: 0.75rem 1rem;
min-width: 10rem;
font-size: 1.6rem;
border-radius: 2rem;
text-align: center;
color: #333;
border: 1px solid #333;
transition: all 0.3s ease-in-out;
}
.radio-selector label:hover {
background-color: lightpink;
cursor: pointer;
}
.radio-selector input:checked + label {
color: white;
background-color: purple;
border: 1px solid transparent;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset class="radio-selector">
<input type="checkbox" id="day-1" name="days" value="1" />
<label for=day-1 class="radio-btn">+- 1 day</label>
<input type="checkbox" id="day-3" name="days" value="3" />
<label for=day-3 class="radio-btn">+- 3 days</label>
<input type="checkbox" id="day-7" name="days" value="7" />
<label for=day-7 class="radio-btn">+- 7 days</label>
</fieldset>
此 javascript 有助于取消选择文档中的每个无线电:
function toggleRadio(event)
{
if(event.target.type === 'radio' && event.target.checked === true)
{
setTimeout(()=>{ event.target.checked = false; },0);
}
}
document.addEventListener('mouseup', toggleRadio);
body { font-size: .55em; }
table { border-collapse: collapse; margin: 0 auto; }
td, th { border: 1px solid #333333; }
td:first-child { padding: 0 0.7em; }
#scale { font-weight:bold; text-align:center; }
<p id="scale">
5 = Excellent | 4 = Satisfactory | 3 = About Average | 2 = Unsatisfactory | 1 = Very Poor
</p>
<table>
<thead>
<tr>
<th> </th> <th>5</th> <th>4</th> <th>3</th> <th>2</th> <th>1</th>
</tr>
</thead>
<tbody>
<tr>
<td>How do rate the default behavior of radios inputs in HTML?</td>
<td><input type="radio" name="r1" value="5" required></td>
<td><input type="radio" name="r1" value="4"></td>
<td><input type="radio" name="r1" value="3"></td>
<td><input type="radio" name="r1" value="2"></td>
<td><input type="radio" name="r1" value="1"></td>
</tr>
<tr>
<td>How do rate this code's ability to deselect radios?</td>
<td><input type="radio" name="r2" value="5" required></td>
<td><input type="radio" name="r2" value="4"></td>
<td><input type="radio" name="r2" value="3"></td>
<td><input type="radio" name="r2" value="2"></td>
<td><input type="radio" name="r2" value="1"></td>
</tr>
</tbody>
</table>
这种方法的优势:
- 取消选择是通过单击当前选定的无线电来实现的。
- 代码不需要任何 DOM 搜索来获取无线电元素。 在
- 页面加载后以编程方式添加到文档中的单选输入也将是可取消选择的。 仅创建一个事件侦听
- 器来为所有无线电提供服务(而不是为每个无线电创建一个事件侦听器)。
- 代码可以在页面加载之前或之后运行,并且它仍然工作相同。
此处讨论了此代码的用户体验注意事项。
如果我的答案已经回答了,但老实说,我很快就读完了它们,因为有这么多
我不是那么熟练,但我想我找到了一种非常简单的方法,只需再次单击即可取消选中已经选中的单选按钮......只需一个全局 var、一个小函数和 onclick 事件
<script>
var lastChecked = null;
function unckeck(myRadio)
{
if ( lastChecked == myRadio )
{
lastChecked = null;
myRadio.checked = false;
}
else
lastChecked = myRadio;
}
</script>
<form>
<input type='radio' name='someCommonName' value='foo' onclick='uncheck(this)'/> foo <br/>
<input type='radio' name='someCommonName' value='bar' onclick='uncheck(this)'/> bar <br/>
<input type='radio' name='someCommonName' value='baz' onclick='uncheck(this)'/> baz <br/>
</form>
单选按钮的 checked
属性来取消选中它。
像这样:
<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>
在这里看到它的实际应用: http://jsfiddle.net/wgYNa/
完整的代码将如下所示
<!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>
<</div>
div class="answers"> 下面是一个示例,说明取消选中单选按钮而不是通过进行新选择是合适的。我有一个字典,可以使用各种索引选择其条目。使用哪个索引是通过一组单选按钮来选择的。但是,还有一个"随机输入"按钮,如果用户只想浏览,可以使用该按钮。通过随机输入按钮选择条目时保留索引将具有误导性,因此当按下此按钮时,我取消选中所有索引选择单选按钮,并将索引框架的内容替换为空页。
如果您使用 Iclick 插件,它就像您在下面看到的那样简单。
$('#radio1').iCheck('uncheck');
<</div>
div class="answers"> 不幸的是,它不能在Chrome或Edge中工作,但它在FireFox中确实有效:
$(document)
// uncheck it when clicked
.on("click","input[type='radio']", function(){ $(this).prop("checked",false); })
// re-check it if value is changed to this input
.on("change","input[type='radio']", function(){ $(this).prop("checked",true); });
Shmili Breuer 答案的无错误更新。
(function() {
$( "input[type='radio'].revertible" ).click(function() {
var $this = $( this );
// update and remove the previous checked class
var $prevChecked = $('input[name=' + $this.attr('name') + ']:not(:checked).checked');
$prevChecked.removeClass('checked');
if( $this.hasClass("checked") ) {
$this.removeClass("checked");
$this.prop("checked", false);
}
else {
$this.addClass("checked");
}
});
})();
这几乎对我有用。
<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");
};
})
但是,如果我选中一个单选按钮,然后选中另一个并尝试再次检查第一个,我必须单击两次。这是因为它已将类选中。我只需要在验证之前取消选中其他单选按钮。
添加此行使其正常工作:
$("input[name='radioBtn']").not(thisRadio).removeClass("imChecked");
<input type='radio' name='radioBtn'>
<input type='radio' name='radioBtn'>
<input type='radio' name='radioBtn'>
$(document).on("click", "input[name='radioBtn']", function(){
thisRadio = $(this);
$("input[name='radioBtn']").not(thisRadio).removeClass("imChecked");
if (thisRadio.hasClass("imChecked")) {
thisRadio.removeClass("imChecked");
thisRadio.prop('checked', false);
} else {
thisRadio.prop('checked', true);
thisRadio.addClass("imChecked");
};
})
下面的代码就可以了。
$('input[type=radio]').click(function() {
if($(this).hasClass("checked")){
this.checked = false;
$(this).removeClass("checked")
}else{
$(this).addClass("checked")
}
});
- 可以'不要通过背景点击来取消自定义UI引导模式
- 通过选中和取消选中复选框来添加和删除数组中的值
- 如何通过jQuery选中所有复选框并在单击一个复选框时取消选择
- 是否可以通过Primefaces 3.3的自定义对话框取消Ajax请求
- 取消选中通过开机自检 [] 中的回显选中的复选框
- 通过在d3中单击来选择/取消选择
- 如何通过javascript中的按钮点击来选择和取消选择多个复选框
- 主干事件未通过取消委托清除
- Javascript:通过另一个函数取消提示
- 通过javascript函数取消设置php数组元素
- 通过 Javascript 保存/取消输入
- 复选框不能通过直接单击复选框来选中或取消选中
- 如何通过JavaScript动态选中/取消选中html复选框
- 如何通过单击单选按钮使其取消选中
- 如何通过 JavaScript 取消隐藏隐藏的 asp 元素
- 当我通过javascript添加警报并取消事件时,滚动条消失了
- 无法通过单击取消按钮停止 ajax 调用
- 通过 JavaScript 中的 Web Audio API 静音/取消静音和更改音量
- 如何通过单击“取消”按钮取消文件上传
- 如果我通过javascript设置不透明度,CSS悬停事件将被取消