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:
考虑两个名称相同的无线电类型输入。当提交时,选中的那个将确定与表单一起发送的值:
<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.
当取消选择单选按钮时,change事件不会触发。因此,如果已经选择了值为“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.
P.S. 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之所以有效,是因为它更改了选中或取消选中时提交的值。我希望单选按钮更像一个选择元素的onchange,但是你能做什么呢?
13 个解决方案
#1
119
<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>
#2
72
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. - 使用onclick处理程序而不是onchange——您正在更改广播输入的“检查状态”,而不是值,因此不会发生更改事件。
- Use a single function, and pass
this
as a parameter, that will make it easy to check which value is currently selected. - 使用一个函数,并将其作为参数传递,这样就可以很容易地检查当前选择的值。
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;
}
#3
23
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).
单击和更改事件在选择单选按钮选项时都被触发(至少在某些浏览器中)。
I should also point out that in my example the click
event is still fired when you use tab and the keyboard to select an option.
我还应该指出,在我的示例中,当您使用tab和键盘选择一个选项时,单击事件仍然被触发。
So, my point is that even though the change
event is fired is some browsers, the click
event should supply the coverage you need.
因此,我的观点是,即使更改事件是由某些浏览器触发的,单击事件也应该提供所需的覆盖率。
#4
5
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/
#5
5
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>
#6
5
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/
#7
4
As you can see here: http://www.w3schools.com/jsref/event_onchange.asp The 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.
第一个问题是由您提供的答案:使用onclick事件,并检查它触发的函数内部的单选按钮状态。
#8
4
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元素,我们从不担心其中的每个选项,而是只选择所选的选项。我们将当前值存储在一个变量中,当选择一个新选项时,该变量将成为先前的值。同样,您必须使用一个单独的变量来存储选中的单选按钮的值。
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/
看到这个:http://jsfiddle.net/diode/tywx6/2/
#9
3
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
将之前检查过的广播存储在一个变量中:http://jsfiddle.net/dsbonev/C5S4B/
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
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
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);
#10
2
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将被存储为一个变量,但是您可能希望首先使用一个临时变量来确保该变量的值发生了更改,因为单击事件将触发是否检查新的单选按钮。
#11
2
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
#12
2
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
如果您希望避免内联脚本,您可以简单地侦听收音机上的单击事件。这可以通过监听单击事件来实现
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
#13
0
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio button
这是最简单、最有效的函数,只需添加任意数量的按钮,并将每个单选按钮的onclick事件调用此函数。为每个单选按钮指定一个唯一的数字
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
}
#1
119
<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>
#2
72
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. - 使用onclick处理程序而不是onchange——您正在更改广播输入的“检查状态”,而不是值,因此不会发生更改事件。
- Use a single function, and pass
this
as a parameter, that will make it easy to check which value is currently selected. - 使用一个函数,并将其作为参数传递,这样就可以很容易地检查当前选择的值。
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;
}
#3
23
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).
单击和更改事件在选择单选按钮选项时都被触发(至少在某些浏览器中)。
I should also point out that in my example the click
event is still fired when you use tab and the keyboard to select an option.
我还应该指出,在我的示例中,当您使用tab和键盘选择一个选项时,单击事件仍然被触发。
So, my point is that even though the change
event is fired is some browsers, the click
event should supply the coverage you need.
因此,我的观点是,即使更改事件是由某些浏览器触发的,单击事件也应该提供所需的覆盖率。
#4
5
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/
#5
5
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>
#6
5
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/
#7
4
As you can see here: http://www.w3schools.com/jsref/event_onchange.asp The 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.
第一个问题是由您提供的答案:使用onclick事件,并检查它触发的函数内部的单选按钮状态。
#8
4
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元素,我们从不担心其中的每个选项,而是只选择所选的选项。我们将当前值存储在一个变量中,当选择一个新选项时,该变量将成为先前的值。同样,您必须使用一个单独的变量来存储选中的单选按钮的值。
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/
看到这个:http://jsfiddle.net/diode/tywx6/2/
#9
3
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
将之前检查过的广播存储在一个变量中:http://jsfiddle.net/dsbonev/C5S4B/
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
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
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);
#10
2
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将被存储为一个变量,但是您可能希望首先使用一个临时变量来确保该变量的值发生了更改,因为单击事件将触发是否检查新的单选按钮。
#11
2
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
#12
2
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
如果您希望避免内联脚本,您可以简单地侦听收音机上的单击事件。这可以通过监听单击事件来实现
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
#13
0
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio button
这是最简单、最有效的函数,只需添加任意数量的按钮,并将每个单选按钮的onclick事件调用此函数。为每个单选按钮指定一个唯一的数字
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
}