Home > Web Front-end > JS Tutorial > body text

How to Capture Radio Button Deselection Events: Beyond onChange Limitations

Susan Sarandon
Release: 2024-10-30 10:24:27
Original
190 people have browsed it

How to Capture Radio Button Deselection Events: Beyond onChange Limitations

Radio Button Confusion: Resolving onChange Limitations

Radio buttons provide a convenient way to handle single selections, but capturing their full state changes can be challenging. Consider a scenario where we have multiple radio buttons with the same name and need to track both selections and deselections.

The onChange event seems like an obvious choice, but it doesn't fire when a radio button is deselected. This creates a problem in scenarios where we need to capture both checked and unchecked events.

Workaround

One workaround is to utilize the addEventListener method and attach a change event handler to each radio button. Inside the event handler, we can maintain a reference to the previously checked radio button (prev) using a variable.

When a radio button is checked, we log both the previous value (prev.value) and the current value (this.value). This allows us to capture both checked and unchecked events.

<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

The accompanying HTML code:

<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

With this workaround, we have a generalized solution that captures onChange events for all radio buttons, including deselection events.

The above is the detailed content of How to Capture Radio Button Deselection Events: Beyond onChange Limitations. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!