Explain Codes LogoExplain Codes Logo

Onchange event handler for radio button (INPUT type="radio") doesn't work as one value

javascript
event-handling
radio-buttons
cross-browser-testing
Anton ShumikhinbyAnton Shumikhin·Sep 19, 2024
TLDR

To track changes on a group of radio buttons, JavaScript provides querySelectorAll and addEventListener to attach a change event. See the minimalistic code snippet:

document.querySelectorAll('input[type="radio"][name="groupName"]').forEach(radio => { radio.addEventListener('change', () => console.log(radio.value)); });

Key Points:

  • querySelectorAll fetches all radio buttons in a group.
  • forEach step by step assigns the change event to each radio button.
  • addEventListener takes care of changes in radio buttons' state.
  • console.log(radio.value) this can be swapped with your actual business logic.

Efficient state tracking

Monitor the state of your radio buttons by keeping track of a previously checked button. Introduce a variable to serve this purpose. This enhances better UI interaction and logical flow:

let lastCameo; // Who was the last star? document.querySelectorAll('input[type="radio"][name="groupName"]').forEach((button) => { button.addEventListener('change', function() { if (this.checked) { // Wasn't someone else the star a moment ago? 🤔 console.log(`Previous choice: ${lastCameo || "N/A"}; New hot pick: ${this.value}`); lastCameo = this.value; // Oh, we have a new star! 🌟 } }); });

Grouping radio buttons using forms

Using an HTML <form> is a smart choice to group your radio buttons logically. It not only lets you manipulate these radio buttons easily but it provides a better structure and integration facility with backend systems.

Supporting keyboard interactions

Many users love their keyboards more than their mouse. So, while change event covers mouse as well as keyboard interactions, it doesn’t hurt to double-check it with a click event listener.

Cross-browser event handling

Web standards and best practices are mindfully established. However, browsers interpret these standards with a tinge of personality. This personality sometimes creates inconsistencies in how an event is handled. Thus, it's vital to perform a cross-browser testing.

Accessible for all

A program should be universally accessible. With ARIA attributes, you can make sure that your form elements, including radio buttons, are usable by everyone.

The crux - The 'this' keyword

While event handlers are like supervisors overseeing an event, the 'this' keyword is their assistant, helping them to know more about the incidents (events).