Workaround for OnChange Event in Radio Button Value
When using radio buttons with the same name, you may encounter a limitation where the onChange event does not trigger when a radio button is deselected. This can create difficulties in tracking the previously selected value.
Solution Approach
To overcome this, you can use a combination of techniques:
Within Event Listener: Within the event listener, the following actions occur:
Code Example:
<code class="js">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); }); }
Example Form:
<code class="html"><form name="myForm"> <input type="radio" name="myRadios" value="1"> <input type="radio" name="myRadios" value="2"> </form></code>
Additional Notes:
The above is the detailed content of How to Track Deselected Radio Button Values with OnChange Events?. For more information, please follow other related articles on the PHP Chinese website!