Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery append lose style

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

like image 788
tmac12 Avatar asked Sep 28 '17 12:09

tmac12


People also ask

How to append text with jQuery?

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.

How to append a child in jQuery?

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() ).

How to add div using jQuery?

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.


1 Answers

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:

  1. create the checkbox in el
  2. append the el to the #mainDiv
  3. reinitialize all js/css that makes it pretty with el.bootstrapToggle()
like image 69
Unamata Sanatarai Avatar answered Oct 17 '22 17:10

Unamata Sanatarai