Javascript 单选按钮 (INPUT type="radio") 的 OnChange 事件处理程序不能作为一个值工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8838648/
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
OnChange event handler for radio button (INPUT type="radio") doesn't work as one value
提问by Matthew
I'm looking for a generalized solution for this.
我正在为此寻找一个通用的解决方案。
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:
考虑 2 个具有相同名称的无线电类型输入。提交时,被检查的那个决定了与表单一起发送的值:
<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />
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.
取消选择单选按钮时不会触发更改事件。因此,如果已经选择了 value="1" 的单选并且用户选择了第二个,则 handleChange1() 不会运行。这带来了一个问题(无论如何对我来说),因为没有任何事件我可以捕捉到这个取消选择。
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.
我想要的是复选框组值的 onchange 事件的解决方法,或者是一个 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.
我相信你们中的一些人以前遇到过这个问题。有哪些解决方法(或者理想情况下处理此问题的正确方法是什么)?我只想捕捉更改事件,访问以前检查过的收音机以及新检查过的收音机。
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.
PS
onclick 似乎是一个更好的(跨浏览器)事件来指示何时选中收音机,但它仍然不能解决未选中的问题。
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...
我想为什么复选框类型的 onchange 在这样的情况下确实有效是有道理的,因为它会在您选中或取消选中它时更改它提交的值。我希望单选按钮的行为更像 SELECT 元素的 onchange 但你能做什么...
采纳答案by Michal
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
</form>
Here's a JSFiddle demo: https://jsfiddle.net/crp6em1z/
这是一个 JSFiddle 演示:https://jsfiddle.net/crp6em1z/
回答by Nate Cook
I would make two changes:
我会做两个改变:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
- Use the
onclick
handler instead ofonchange
- you're changing the "checked state" of the radio input, not thevalue
, so there's not a change event happening. - Use a single function, and pass
this
as a parameter, that will make it easy to check which value is currently selected.
- 使用
onclick
处理程序而不是onchange
- 您正在更改无线电输入的“已检查状态”,而不是value
,因此不会发生更改事件。 - 使用单个函数,并
this
作为参数传递,这样可以轻松检查当前选择了哪个值。
ETA: Along with your handleClick()
function, you can track the original / old value of the radio in a page-scoped variable. That is:
ETA:与您的handleClick()
功能一起,您可以在页面范围的变量中跟踪收音机的原始/旧值。那是:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
回答by Philip Walton
As you can see from this example: http://jsfiddle.net/UTwGS/
正如你从这个例子中看到的:http: //jsfiddle.net/UTwGS/
HTML:
HTML:
<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>
jQuery:
jQuery:
$('input[type="radio"]').on('click change', function(e) {
console.log(e.type);
});
both the click
and change
events are fired when selecting a radio button option (at least in some browsers).
无论是click
和change
选择(在一些浏览器至少)单选按钮选项,当事件被触发。
I should also point out that in my example the click
event is still firedwhen you use tab and the keyboard to select an option.
我还应该指出,在我的示例中,当您使用选项卡和键盘选择一个选项时,该click
事件仍然会被触发。
So, my point is that even though the change
event is fired is some browsers, the click
event should supply the coverage you need.
所以,我的观点是,即使change
事件是由某些浏览器触发的,该click
事件也应该提供您需要的覆盖范围。
回答by Razan Paul
What about using the change event of Jquery?
使用jquery的change事件怎么样?
$(function() {
$('input:radio[name="myRadios"]').change(function() {
if ($(this).val() == '1') {
alert("You selected the first option and deselected the second one");
} else {
alert("You selected the second option and deselected the first one");
}
});
});
jsfiddle: http://jsfiddle.net/f8233x20/
jsfiddle:http: //jsfiddle.net/f8233x20/
回答by Constantin Gro?
As you can see here: http://www.w3schools.com/jsref/event_onchange.aspThe onchange attribute is not supported for radio buttons.
正如您在此处看到的:http: //www.w3schools.com/jsref/event_onchange.asp单选按钮不支持 onchange 属性。
The first SO question linked by you gives you the answer: Use the onclick
event instead and check the radio button state inside of the function it triggers.
您链接的第一个 SO 问题为您提供了答案:改用onclick
事件并检查它触发的函数内的单选按钮状态。
回答by Alex Okrushko
I don't think there is any way other then storing the previous state. Here is the solution with jQuery
我认为除了存储以前的状态之外没有任何其他方法。这是jQuery的解决方案
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var lastSelected;
$(function () {
//if you have any radio selected by default
lastSelected = $('[name="myRadios"]:checked').val();
});
$(document).on('click', '[name="myRadios"]', function () {
if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
}
lastSelected = $(this).val();
});
</script>
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />
After thinking about it a bit more, I decided to get rid of the variable and add/remove class. Here is what I got: http://jsfiddle.net/BeQh3/2/
再想一想,我决定去掉变量并添加/删除类。这是我得到的:http: //jsfiddle.net/BeQh3/2/
回答by John K
I realize this is an old issue, but this snippet of code works for me. Perhaps someone in the future will find it useful:
我意识到这是一个老问题,但这段代码对我有用。也许将来有人会发现它很有用:
<h2>Testing radio functionality</h2>
<script type="text/javascript">var radioArray=[null];</script>
<input name="juju" value="button1" type="radio" onclick="radioChange('juju','button1',radioArray);" />Button 1
<input name="juju" value="button2" type="radio" onclick="radioChange('juju','button2',radioArray);" />Button 2
<input name="juju" value="button3" type="radio" onclick="radioChange('juju','button3',radioArray);" />Button 3
<br />
<script type="text/javascript">
function radioChange(radioSet,radioButton,radioArray)
{
//if(radioArray instanceof Array) {alert('Array Passed');}
var oldButton=radioArray[0];
if(radioArray[0] == null)
{
alert('Old button was not defined');
radioArray[0]=radioButton;
}
else
{
alert('Old button was set to ' + oldButton);
radioArray[0]=radioButton;
}
alert('New button is set to ' + radioArray[0]);
}
</script>
回答by Diode
Yes there is no change event for currently selected radio button. But problem is when each radio button is taken as a separate element. Instead a radio group should be considered a single element like select
. So change event is triggered for that group. If it is a select
element we never worry about each option in it, but take only the selected option. We store the current value in a variable which will become the previous value, when a new option is selected. Similarly you have to use a separate variable for storing value of checked radio button.
是的,当前选定的单选按钮没有更改事件。但问题是当每个单选按钮都被视为一个单独的元素时。相反,应该将无线电组视为单个元素,例如select
. 因此为该组触发更改事件。如果它是一个select
元素,我们从不关心其中的每个选项,而只考虑选定的选项。We store the current value in a variable which will become the previous value, when a new option is selected. 同样,您必须使用单独的变量来存储选中单选按钮的值。
If you want to identify the previous radio button, you have to loop on mousedown
event.
如果要识别上一个单选按钮,则必须在mousedown
事件上循环。
var radios = document.getElementsByName("myRadios");
var val;
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
val = radios[i].value;
}
}
see this : http://jsfiddle.net/diode/tywx6/2/
回答by Dimitar Bonev
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
将之前检查的收音机存储在一个变量中:http:
//jsfiddle.net/dsbonev/C5S4B/
HTML
HTML
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5
JS
JS
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
//using radio elements previousCheckedRadio and currentCheckedRadio
//storing radio element for using in future 'change' event handler
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
JS EXAMPLE CODE
JS 示例代码
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
function logInfo(info) {
if (!console || !console.log) return;
console.log(info);
}
function logPrevious(element) {
if (!element) return;
var message = element.value + ' was unchecked';
logInfo(message);
}
function logCurrent(element) {
if (!element) return;
var message = element.value + ' is checked';
logInfo(message);
}
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
logPrevious(previousCheckedRadio);
logCurrent(currentCheckedRadio);
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
回答by Andrew Latham
This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.
这只是我的头顶,但你可以为每个单选按钮做一个 onClick 事件,给他们所有不同的 ID,然后在事件中创建一个 for 循环来遍历组中的每个单选按钮并找到哪个是通过查看“已检查”属性进行检查。被检查的 ID 将被存储为一个变量,但您可能希望首先使用一个临时变量来确保该变量的值已更改,因为无论是否选中新的单选按钮,单击事件都会触发。