jQuery append lose style

Viewed 2301

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

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

Here you go with one more 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.github.io/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.github.io/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 append the checkbox to the mainDiv, find the latest added element using jQuery last method then reinitialise to bootstrap toggle.

Hope this will help you.

Related