Hello. I've wrote a simple script that dynamically adds controls to my form. It works in FF and Opera perfectly, but doesn't work in IE. Help me to find a cause. Thanks.

var counter = 1;
        function addInput(){
                  var newtr = document.createElement('tr');
                  var td1 = document.createElement('td');
                  var td2 = document.createElement('td');
                  var inp = document.createElement('select');
                  inp.name = 'stations['+counter+'].id';
                  var opt = document.createElement('option');
                  stationList = document.getElementById('stationsList').childNodes;
                  var options = new Array();
                  for(var i = 0; i < stationList.length; i++){
                      options[i] = document.createElement('option');
                      options[i].text = stationList[i].text;
                      options[i].value = stationList[i].value;
                      inp.appendChild(options[i]);
                  }
                  td1.innerHTML = "Station #" + (counter + 1);
                  td2.appendChild(inp);
                  newtr.appendChild(td1);
                  newtr.appendChild(td2);
                  document.getElementById('stat').appendChild(newtr);
                  counter++;
        }
  • A little bit of HTML would help and also describing what is does differently in IE. Mottie almost 7 years ago

1 answer

Mottie 1134
3
points

Ok, I'm guessing your appended drop down menus don't work in IE but they do in other browsers. This is because of this line:

options[i].text = stationList[i].text;

.text is a shortcut to get the tag text, but it doesn't work when using it to set the text (at least not in IE). Try switching this to .innerText or .innerHTML

options[i].innerText = stationList[i].text;

Also, if you haven't looked into using a javascript library, I'd recommend looking into using jQuery. It will make the coding of this function easier (in my opinion). I made a function that does essentially the same thing your addInput function does using mostly text, then appending that into the table.

I am assuming this HTML

<select id="stationsList">
 <option value="s1">x1</option>
 <option value="s2">x2</option>
 <option value="s3">x3</option>
 <option value="s4">x4</option>
 <option value="s5">x5</option>
</select>

<table id="stat"></table>

to work with this script:

function addInput2(){
 var stationList = $('#stationsList option'); // I am assuming the list is in a set of options
 var inp = '<select name="stations['+counter+'].id">';
 for(var i = 0; i < stationList.length; i++){
  inp += '<option value="' + stationList[i].value + '">' + stationList[i].text + '</option>';
 }
 inp += '</select>';
 var newtr = '<tr><td>Station #' + (counter + 1) + '</td><td>' + inp + '</td>';
 $('#stat').append(newtr);
 counter++;
}
Answered almost 7 years ago by Mottie