Home > Web Front-end > JS Tutorial > How to Track Deselected Radio Button Values with OnChange Events?

How to Track Deselected Radio Button Values with OnChange Events?

DDD
Release: 2024-10-29 03:57:02
Original
371 people have browsed it

How to Track Deselected Radio Button Values with OnChange Events?

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:

  1. Iterate Over Radio Buttons: Iterate over all radio buttons with the same name using JavaScript.
  2. Event Listener for Change: Add an event listener for the change event to each radio button.
  3. Previous Radio: Initialize a variable, prev, outside the event listener to initially store a null value.
  4. Within Event Listener: Within the event listener, the following actions occur:

    • If there is a prev value, log its value to the console.
    • Update the prev value to the current radio button.
    • Log the value of the current radio button to the console.

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);
    });
}
Copy after login

Example Form:

<code class="html"><form name="myForm">
  <input type="radio" name="myRadios"  value="1">
  <input type="radio" name="myRadios"  value="2">
</form></code>
Copy after login

Additional Notes:

  • This approach allows you to track both the previously selected and the newly selected radio button values.
  • The concept can be extended to handle multiple groups of radio buttons.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template