JQuery append is losing style

I have a problem when I try to use the jQuery add function, it adds an element to a div, but it loses 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 js:

 $('#btnAdd').click(function(){ $('#mainDiv').append(' <input type="checkbox" data-toggle="toggle"/>'); }) 

My input style is bootstrap-toggle.

Can you help me? Thanks

+7
javascript jquery html css twitter-bootstrap
source share
2 answers

You must reinitialize the switch because initialization occurs when the document is loaded. Not on the fly.

Jsfiddle

 $('#btnAdd').click(function(){ var el = $(' <input type="checkbox" data-toggle="toggle"/>'); $('#mainDiv').append(el); el.bootstrapToggle(); }) 

description:

  • check the box in el
  • add el to #mainDiv
  • reinitialize all js / css, which makes it pretty with el.bootstrapToggle()
+9
source share

Here you will find another solution https://jsfiddle.net/a3nq8aky/4/

 $('#btnAdd').click(function(){ $('#mainDiv') .append(' <input type="checkbox" data-toggle="toggle"/>') .find('input[type="checkbox"]') .last() .bootstrapToggle(); }) 
 <link href="https://gitcdn.imtqy.com/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js"></script> <script src="https://gitcdn.imtqy.com/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script> <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> </form> 

Once you add the checkbox to mainDiv , find the last item added using the jQuery last method, then reinitialize to bootstrap toggle .

Hope this helps you.

0
source share

All Articles