I have a problem when I try to use append function of jQuery, it add element to a div but it lose style. This is an example here
This is my html:
<form>
<div class="checkbox">
<label>
<input type="checkbox" data-toggle="toggle" checked="checked" />
Toggle One
</label>
</div>
<div id="mainDiv">
</div>
<div>
<button type="button" class="btn btn-default" id="btnAdd">
Add
</button>
</div>
and this is the js:
$('#btnAdd').click(function(){
$('#mainDiv').append(' <input type="checkbox" data-toggle="toggle"/>');
})
The style of my input is bootstrap-toggle.
Can you help me? Thanks
jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
The .append() method inserts the specified content as the last child of each element in the jQuery collection (To insert it as the first child, use .prepend() ).
There are various method to create HTML element inside an HTML document using JQuery. But the simplest of all is append() and prepend() method. Method 1: Using prepend() Method: The prepend() method is used to insert a specified content at the beginning of the selected element.
You must reinitialize the toggle, as the initialization happens on document load. Not on the fly.
JsFiddle
$('#btnAdd').click(function(){
var el = $(' <input type="checkbox" data-toggle="toggle"/>');
$('#mainDiv').append(el);
el.bootstrapToggle();
})
description:
el
el
to the #mainDiv
el.bootstrapToggle()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With