用于单选按钮(INPUT type =“radio”)的OnChange事件处理程序不作为一个值工作 [英] OnChange event handler for radio button (INPUT type="radio") doesn't work as one value
问题描述
我正在寻找一个全面的解决方案。
I'm looking for a generalized solution for this.
考虑使用相同名称的2个无线电类型输入。提交时,被检查的值确定以下面形式发送的值:
Consider 2 radio type inputs with the same name. When submitted, the one that is checked determines the value that gets sent with the form:
<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />
取消选择单选按钮时,更改事件不会触发。因此,如果值为1的收音机已经被选择,并且用户选择了第二个,handleChange1()不运行。这提出了一个问题(对我来说),没有事件,我可以赶上这个取消选择。
The change event does not fire when a radio button is de-selected. So if the radio with value="1" is already selected and the user selects the second, handleChange1() does not run. This presents a problem (for me anyway) in that there is no event where I can can catch this de-selection.
我想要的是一个解决方案onchange
What I would like is a workaround for the onchange event for the checkbox group value or alternatively an oncheck event that detects not only when a radio is checked but also when it is unchecked.
我相信你们中的一些人已经拥有了一个复选框组值,或者一个oncheck事件,它不仅检测收音机是否被检查,遇到这个问题之前。什么是一些解决方法(或理想情况下,正确的方式来处理这个)?我只想捕获更改事件,访问以前检查过的收音机以及新检查的收音机。
I'm sure some of you have run into this problem before. What are some workarounds (or ideally what is the right way to handle this)? I just want to catch the change event, access the previously checked radio as well as the newly checked radio.
PS
onclick似乎更好(跨浏览器)事件,以指示何时检查收音机,但仍然无法解决未检查的问题。
P.S.
onclick seems like a better (cross-browser) event to indicate when a radio is checked but it still does not solve the un-checked problem.
我想这是有道理为什么onchange的复选框类型在这样的情况下工作,因为它会更改提交的值,当您检查或取消检查它。我希望单选按钮的行为更像一个SELECT元素的onchange,但你能做什么...
I suppose it makes sense why onchange for a checkbox type does work in a case like this since it changes the value that it submits when you check or un-check it. I wish the radio buttons behaved more like a SELECT element's onchange but what can you do...
推荐答案
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
</form>
<script>
var rad = document.myForm.myRadios;
var prev = null;
for(var i = 0; i < rad.length; i++) {
rad[i].onclick = function() {
(prev)? console.log(prev.value):null;
if(this !== prev) {
prev = this;
}
console.log(this.value)
};
}
</script>
这篇关于用于单选按钮(INPUT type =“radio”)的OnChange事件处理程序不作为一个值工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!