javascriptcheckboxbootstrap-4

Fire bootstrap JS after inserting DOM element on the fly


I use bootstrap-toogle for fancy checkbox. It works on page load, but if I insert an input element on the fly via JS it shows the default checkbox.

<link rel="stylesheet" href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>

<div class="row"><label for="button_1">Button 1 </label><input type="checkbox" id="button_1" name="button_1" checked="checked" data-toggle="toggle"></div>
<div id="add">ADD button</div>

<script type="text/javascript">
$(document).on("click", "#add", function() {
    var number = $("div.row").length + 1;
    var content = "<div class=\"row\"><label for=\"button_"+number+"\">Button "+number+" </label><input type=\"checkbox\" id=\"button_"+number+"\" name=\"button_"+number+"\" checked=\"checked\" data-toggle=\"toggle\"></div>";
    $("div.row").last().after(content);
});
</script>

Here is a fiddle: https://jsfiddle.net/8w3dk264/

Is there a way I can fire bootstrap-toogle code after inserting element on the fly?

Thanks,


Solution

  • OMG I should have read the manual :(

    It was that easy:

    $(elem).bootstrapToggle();
    

    Sorry,