how to use only Javascript to add new Bootstrap switch dynamically
like this:
<div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width: 61.0781px; height: 38px;">
<input type="checkbox" checked="" data-toggle="toggle" data-onstyle="primary">
<div class="toggle-group">
<label class="btn btn-primary toggle-on">
On
</label>
<label class="btn btn-light toggle-off">
Off
</label>
<span class="toggle-handle btn btn-light">
</span>
</div>
</div>
from this site text
button can be added like this
<script>
function addButton() {
var element = document.createElement("input");
element.type = "button";
element.value = "View Info";
element.name = "getInfo";
element.className = "btn btn-info btn-lg";
}
</script>
function addButton() {
var element = document.createElement("input");
element.type = "button";
element.value = "View Info";
element.name = "getInfo";
element.className = "btn btn-info btn-lg";
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/js/bootstrap4-toggle.min.js"></script>
<div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width: 61.0781px; height: 38px;">
<input type="checkbox" checked="" data-toggle="toggle" data-onstyle="primary">
<div class="toggle-group">
<label class="btn btn-primary toggle-on">
On
</label>
<label class="btn btn-light toggle-off">
Off
</label>
<span class="toggle-handle btn btn-light">
</span>
</div>
</div>
2
Answers
You’d need a parent element in your HTML under which you’d add this newly created switch.
Say you have a
div#switch-host
in your HTML.Then you’d implement a JS function which will add your switch to this div as
And then call this function as
I think this is what you are after. I used some template because I don’t like all that in code. I then modified the values with jQuery since this is a jQuery plugin.
Ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template