jquerybootstrap-5buttongroup

No JavaScript event firing for Boostrap 5 button group


Correct me if I'm wrong, but it seems like the button group in Bootstrap 5 does not fire an event on click or change anymore? How would you detect change in JavaScript, preferably? In Boostrap 3, we've used $('.btn-group').on('change', ...).

See code: https://getbootstrap.com/docs/5.0/components/button-group/#checkbox-and-radio-button-groups

Copy-pasted from manual:

<div class="btn-group" role="group" aria-label="Basic radio toggle button group">
  <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked>
  <label class="btn btn-outline-primary" for="btnradio1">Radio 1</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio2">Radio 2</label>

  <input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off">
  <label class="btn btn-outline-primary" for="btnradio3">Radio 3</label>
</div>

Solution

  • Bootstrap doesn't fire an event, but the radio group does. Attach change listeners to the radio group inputs...

    const myHandler = (event) => {
         alert('Radio with ID = ' + event.target.id);
    }
    
    document.querySelectorAll("input[name='btnradio']").forEach((input) => {
        input.addEventListener('change', myHandler);
    })
    

    Demo