I have a select list menu:
<label>
<select name="select" id="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</label>
I want to duplicate it with the exact informations dynamically. I can do that by creating a select element and copying the innerHTML from the first select. (I also generate a table row which my select is going to be on, but it’s not important):
var selectt = document.createElement("select");
selectt.setAttribute("name", "select"+counter);
selectt.setAttribute("id", "select"+counter);
selectt.onchange = function() {sellcalculate(counter);
cell3.appendChild(selectt);
document.getElementById("select"+counter).innerHTML=document.getElementById("select1").innerHTML;
It works fine on Firefox, but IE just creates the select but wouldn’t copy the options.
My second question is: how can I add an onchange event to the created element?
selectt.onchange = function(){sellcalculate(counter)};
This doesn’t seems to work.
here is the compelete function after edit function and solving the ie problem :
function addRow(tableID) {
var counter = document.getElementById('rowcounter').value;
counter++;
document.getElementById('rowcounter').value = counter;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell = row.insertCell(0);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.id = "amount" + counter;
element2.onchange = function () {
sellcalculate(counter)
};
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var selectt = document.createElement("select");
selectt = document.getElementById("select1").cloneNode(true);
selectt.setAttribute("name", "select" + counter);
selectt.setAttribute("id", "select" + counter);
selectt.onchange = (function (cntr) {
return function () {
sellcalculate(cntr);
};
})(counter);
cell3.appendChild(selectt);
}
I can’t test in IE right now, but try using
.cloneNode()instead to create the new element.The
trueargument passed to.cloneNodemakes it a deep clone (all descendants).Also, I assumed you want the
onchangehandler to reference the current value ofcounterinstead of a potentially different future value. As such, I scoped the current value using a new function invocation.Now whatever the value of
counteris when this code runs will be the value passed tosellcalculate().