I want to create dynamic switchery and create and button object with jquery and some dynamic variable for this then I want the Html object to append to Html I can't do it below link is my code Visit jsfiddle.net/eu3a0k3m/2/
my js codes:
var count = 3;
$("#btn").click(function(){
CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery (countOfChilds){
var Integer_LastSwitcheryId = count;
var btn = $('<input type="checkbox" id="js-switch' + Integer_LastSwitcheryId + '" class="js-switch' + Integer_LastSwitcheryId + ' js-check-change' + Integer_LastSwitcheryId + ' col-lg-3" data-switchery="true">');
console.log(btn)
$('#all-encyclopedia').append(
$("#tpl ").html()
.replace(/{switchery}/g,btn)
);
eval("elem" + Integer_LastSwitcheryId.toString() + "=document.querySelector('#js-switch"+Integer_LastSwitcheryId.toString()+"')");
eval("switchery" + Integer_LastSwitcheryId.toString() +"={elem" + Integer_LastSwitcheryId.toString() + ", color: '#1AB394',secondaryColor: '#688ab0'}");
eval("changeCheckbox" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change"+Integer_LastSwitcheryId.toString()+"')");
eval("changeField" + Integer_LastSwitcheryId.toString() + "=document.querySelector('.js-check-change-field"+Integer_LastSwitcheryId.toString()+"')");
}
for(i=1;i<4;i++)
CreateInlineChildWithSwitchery(count++);
my Html codes:
<script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia"></div>
You don't need to use eval
. just call the Switchery
constructor after you inserted the checkbox into the page.
var count = 3;
$("#btn").click(function() {
CreateInlineChildWithSwitchery(++count);
});
function CreateInlineChildWithSwitchery(id) {
var btn = $('<input>').attr({
id: 'js-switch' + id,
type: 'checkbox',
class: ['js-switch' + id, 'js-check-change' + id, 'col-lg3'].join(" "),
}).data({
switchery: true,
})[0]
$('#all-encyclopedia').append(
$("#tpl").html().replace(/{switchery}/g, btn.outerHTML));
new Switchery($('#' + 'js-switch' + id)[0], {
color: '#1AB394',
secondaryColor: '#688ab0'
})
}
for (i = 1; i < 4; i++)
CreateInlineChildWithSwitchery(count++);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.css" rel="stylesheet"/>
<script type="text/tpl" id="tpl">
{switchery}
</script>
<button id="btn">insert Switchery</button>
<div id="all-encyclopedia"></div>