I'm trying to make new element using createElement
method. But in this case I want id
attribute should change as variable changes while adding Dynamic Input using Button.
Uncaught SyntaxError: Unexpected identifier
Here, I'm using \n
for new line for formating input in createElement
method.
Below code was working If I remove script
tag. But in this case I want script
tag for using select2.
var personCount = 1;
function addNewInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = '<select style="width: 100%" id="person'+ (personCount + 1) +'"StateInput" ></select>\n\
<script>\n\
$('#person'+ (personCount + 1) +'"StateInput').select2({\n\
ajax: {\n\
url: 'url/for/state',\n\
dataType: 'json'\n\
}\n\
});\n\
</script>';
document.getElementById(divName).appendChild(newdiv);
count++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<select style="width: 100%" id="person1StateInput" ></select>
<script>
$('#Test1A').select2({
ajax: {
url: 'url/state',
dataType: 'json'
}
});
</script>
<div id="add"></div>
<button class="btn btn-primary" onclick="addNewInput('add');">Add Peaky Blinder</button>
The code will explain the problem better rather than a description