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:
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.
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.
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.
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...
Answer
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)
});
}
Here's a JSFiddle demo: https://jsfiddle.net/crp6em1z/
No comments:
Post a Comment