I am trying to add a new select field in HTML form on button click but I have a suspicion that my javascript does not work on my newly created element. I have already searched for this and some people suggest to use jQuery instead of JavaScript but this does not solve my problem either. Here is what I have tried already:
/* BUTTON TO ADD NEW SELECT COMPONENT */
<input type="button" value="Add new" onClick="addInput('dynamicInput');">
/* THIS IS MY JAVASCRIPT WHERE I AM CREATING NEW SELECT */
<script>
var counter = 1;
var limit = 100;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newspan = document.createElement('select');
newspan.className = "form-control populate";
newspan.innerHTML = "<br><select data-plugin-selectTwo class='form-control populate'><option value='VA'>Virginia</option><option value='WV'>West Virginia</option></select>";
document.getElementById(divName).appendChild(newspan);
counter++;
}
}
</script>
/* THIS IS THE STRUCTURE OF THE SELECT ELEMENT I AM TRYING TO ACHIEVE */
<select data-plugin-selectTwo class="form-control populate">
<optgroup label="Alaskan/Hawaiian Time Zone">
<option value="AK">Alaska</option>
<option value="HI">Hawaii</option>
</optgroup>
<optgroup label="Pacific Time Zone">
<option value="CA">California</option>
<option value="NV">Nevada</option>
<option value="OR">Oregon</option>
<option value="WA">Washington</option>
</optgroup>
</select>
</div>
In the above pictures, you can see that the newly created select does not have this "search field".
Please give me a solution with the working code if you can! Thank you!