Sugafree
Sugafree

Reputation: 683

Bootstrap 4 switch change event will not work

I am using multiple Bootstrap 4 switches loaded onto the page by JS append and need to call a function on the switch changes. The following example works when I add the switches in HTML, but when I dynamically load them via JS after page load, it will not work. I DO NOT want to use any other external library for this!

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="customSwitch1">
  <label class="custom-control-label" for="customSwitch1">Toggle this switch element</label>
</div>

I have tried multiple JS code, but none seems to be working. Example

$('.custom-control').on('change', function (e) {
  let value = this.value;
  let test = $(e).target.checked;
});

Also tried using the class of the input tag.

Upvotes: 3

Views: 7202

Answers (2)

SteveKE
SteveKE

Reputation: 11

Try using jQuery alternatively as

$(document).on('change', '.custom-control', function (e) {
    let test = $(this).is(':checked');
    console.log(test);
});

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42054

A checkbox has a checked attribute.

Hence use:

let test = e.target.checked;

Because you add dynamically the switch you need to delegate the change event:

$(document).on('change', '.custom-control', function (e) {

The snippet:

$(document).on('change', '.custom-control', function (e) {
    let test = e.target.checked;
    console.log(test);
});

$('body').append('<div class="custom-control custom-switch">\
        <input type="checkbox" class="custom-control-input" id="customSwitch1">\
        <label class="custom-control-label" for="customSwitch1">Toggle this switch element</label>\
</div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

Upvotes: 7

Related Questions