Reputation: 139
I'm trying to add bootstrap toggle switch dynamically but it does not display well after adding it. Thanks for your help!
<input id="TheCheckBox" type="checkbox" data-off-text="Yes" data-on-text="No" checked="false" class="BSswitch">
<p> <a class="btn btn-lg btn-primary" href="#">Display another Toggle</a></p>
$('.btn').on('click', function () {
$('p').after(
'<input id="TheCheckBox" type="checkbox" data-off-text="Male" data-on-text="Female" checked="false" class="BSswitch">'
);
});
This is the Jsfiddle: http://jsfiddle.net/icamilo95/8wars2ep/3/
Upvotes: 5
Views: 5650
Reputation: 739
I was facing the same issue using bootstrap-toggle. Then after debugging, I understood the behaviour and handled it.
If the checkbox is not in the dom when page loads, then we need to initialize the toggler when the checkbox is available to the dom and also any listener methods.
if you are doing an ajax call then in the success method you can add the following in the end.
$("[data-toggle='toggle']").bootstrapToggle('destroy')
$("[data-toggle='toggle']").bootstrapToggle();
sometimes it may take time to add to the dom and your code gets run before checkbox getting added to the dom, you can wrap the above code in a javascript timer
setTimeout( () => {
$("[data-toggle='toggle']").bootstrapToggle('destroy')
$("[data-toggle='toggle']").bootstrapToggle();
$(".checkbox").change(function() {
console.log("toggled");
});
}, 100 );
Upvotes: 1
Reputation: 41
Add Bootstrap toggle js after your main js file
Then call bootstrapswitch statement in your js file
$('.your_toggle_class_name').bootstrapSwitch('state', true);
Upvotes: 0
Reputation: 32275
You need to call the bootstrapSwitch() again after adding and with a new ID, class or else it will alter the states of existing toggle as well.
$('.btn').on('click', function () {
$('p').after(
'<input id="newCheckBox" type="checkbox" data-off-text="Male" data-on-text="Female" checked="false" class="newBSswitch">'
);
$('.newBSswitch').bootstrapSwitch('state', true); // Add
});
Upvotes: 4