So I've tried a few things, and not really getting anywhere. After an extensive google search I've decided to seek for help from the masters in SO.
The idea: Duplicate a dropdown and a input field on a button click ( can be any number of times )
The solution: JavaScript click listener that takes a copy of the existing div and makes a new one.
The problem: When cloning the div with the dropdown and the input field the JavaScript code does not change the ID's of the child elements making the dropdown unusable( they can be interacted with but I cannot use the data from them ).
I've made a JSFiddle if anyone would like to play with it.
HTML:
<div id="row-container">
<div id="profile-row0">
<select id="select-item0" class="selectpicker" data-live-search="true">
<option>id</option>
<option>email</option>
<option>phone</option>
</select>
<input id="select-item-value0" class="select-item-value" placeholder="Item value"/>
</div>
</div>
<button id="add-button"> GO </button>
JS:
document.getElementById("add-button").addEventListener("click", addItemRow);
var i = 0;
function addItemRow(){
var original = document.getElementById('profile-row' + i);
var clone = original.cloneNode(true);
clone.id = "profile-row" + ++i;
//clone.firstChild.id = "select-item" + ++i;
//clone.lastChild.id = "select-item-value" + ++i;
original.parentNode.appendChild(clone);
}
The last thing I have tried is commented out in the JavaScript code.
Your code almost works, but you missed one thing: the first and last elements aren't the ones you are looking for (These are not the droids... sorry, I couldn't help it). The first and the last elements are #text
nodes, not HtmlElement
ones.
you can modify your code to make it work:
function addItemRow(){
var original = document.getElementById('profile-row' + i);
var clone = original.cloneNode(true);
i++;
clone.id = "profile-row" + i;
clone.getElementsByTagName('select')[0].id = "select-item" + i;
clone.getElementsByTagName('input')[0].id = "select-item-value" + i;
original.parentNode.appendChild(clone);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With