Escher
Escher

Reputation: 5766

Detect change event for radio inputs (with labels styled as buttons) in bootstrap 4

As per the title, I'm trying to detect a change event (that doesn't seem to be occurring when I inspect the DOM) in this jsfiddle. The radio inputs are styled using bootstrap classes. Why aren't I getting a change?

For reference, here's some code:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-sm btn-primary active">
    <input type="radio" name="preview" id="preview-enabled" value="true" autocomplete="off" checked>Alice
  </label>
  <label class="btn btn-sm btn-secondary">
    <input type="radio" name="preview" id="preview-disabled" value="false" autocomplete="off">Bob
  </label>
</div>

The input radios aren't changing when the buttons are clicked.

I'm also getting a weird error that jquery is required for bootstrap's js (however jquery is included before bootstrap's js as per the official instructions)

Upvotes: 2

Views: 1109

Answers (1)

Escher
Escher

Reputation: 5766

The "checked" attribute of the input radio element doesn't change (therefore not triggering the eventListener); it is the underlying DOM property checked of that element that changes.

You would think that the solution therefore would be to listen for changes to the DOM property on that node with a MutationObserver. However this doesn't work either, because it's not a change in the DOM, just a state change. And it seems (without using a shadow DOM framework like React) that there's no way to track this without polling.

Upvotes: 3

Related Questions