skip to Main Content

In JavaScript, is there an event triggered when a radio button is checked?

<input type="radio" name="radio" id="radio1">
<input type="radio" name="radio" id="radio2" checked>
<input type="radio" name="radio" id="radio3">

Is something like the following possible?

document.getElementById("radio1").addEventListener('checked', () => {
    // Do something when the first radio button is checked
})

JSfidde: https://jsfiddle.net/Imabot/ko486uqe/2/

PLEASE read before answering or marking as duplicate. My question is not "How to run JS code when the radio button is checked". My question is "Is there an event triggered only when the radio button is checked", this is not exactly the same thing…

2

Answers


  1. Try this:

    document.getElementById("radio1").addEventListener('change', () => {
        if (document.getElementById("radio1").checked) {
            // Do something when the first radio button is checked
            console.log("radio1 checked");
        }
    });
    
    Login or Signup to reply.
  2. There’s no such special event for radio buttons only.
    There’s not such special event for "radioChecked".

    To test the checked state you need to do it on your own.
    The best would be to use event delegation, check if the element target is a Radio Element, and then go for its cehecked property:

    addEventListener(`input`, (evt) => {
      const elRadio = evt.target.closest(`[type="radio"]`);
      if (!elRadio) return; // Not a radio element. Do nothing
      
      console.log(`${elRadio.id} ${elRadio.checked}`); 
    });
    <input type="radio" name="radio-group-one" id="radio-1">
    <input type="radio" name="radio-group-one" id="radio-2" checked>
    <input type="radio" name="radio-group-one" id="radio-3">

    Whilst using Event.target.closest() is always a good practice, you can also use the Element.matches() method when handling actionElements like input:

    addEventListener(`input`, (evt) => {
      if (!evt.target.matches(`[type="radio"]`)) return; // Do nothing
          
      console.log(`${evt.target.id} ${evt.target.checked}`); 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search