Home > Web Front-end > JS Tutorial > How to Handle Both Check and Uncheck Events for Radio Buttons in JavaScript?

How to Handle Both Check and Uncheck Events for Radio Buttons in JavaScript?

Barbara Streisand
Release: 2024-10-31 05:31:30
Original
660 people have browsed it

How to Handle Both Check and Uncheck Events for Radio Buttons in JavaScript?

OnChange Event for Radio Buttons: Handling Check and Uncheck Events

When working with radio buttons, it's essential to handle both check and uncheck events effectively. The standard onChange event doesn't cater to this, as it only triggers when a radio button is selected. This leaves a gap in identifying when a previous selection is deselected.

Workaround for OnChange Event:

Consider the following code snippet:

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

This script accomplishes the desired behavior:

  1. It iterates over all radio buttons.
  2. For each radio button, an event listener is added to the onChange event.
  3. When a radio button is checked, it logs the value of the previously checked radio button (if there was one) and updates the reference to the currently checked radio button.

This solution captures both check and uncheck events, allowing you to access both the previously and currently checked radio buttons' values.

Limitations of OnClick Event:

The onClick event, while more consistent across browsers, still doesn't address the issue of capturing uncheck events. Hence, while it may be considered for certain use cases, it's not a complete solution for handling both check and uncheck events with radio buttons.

The above is the detailed content of How to Handle Both Check and Uncheck Events for Radio Buttons in JavaScript?. 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