1

I want to populate my drop down list with dynamic values but the list remains empty in other words no option is shown Could someone help me !!! here is my code http://jsfiddle.net/n6ahz/24/

var newdiv = document.createElement('div');
var text="TEXT";
var n=0;
newdiv.innerHTML += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 0;

var options = '';
for (var j = 1; j < 5; j++) {
 var val = "marwa" + j;
if (val) {
    m++;
    options += " <option value="+j+"> " + val + "</option>";
     }
 }
 newdiv.innerHTML += "<select name='single' id='single'>";
 newdiv.innerHTML += " "+options + " </select> ";

document.getElementById('results').appendChild(newdiv);​

3 Answers 3

7

Instead of

newdiv.innerHTML += "<select name='single' id='single'>";
newdiv.innerHTML += " "+options + " </select> ";

try

newdiv.innerHTML += "<select name='single' id='single'> "+options + " </select> ";

I don't think adding HTML a bit at a time works because the browser will try to render it immediately.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank u :) the problem is solved !!! I didn't expect that it has to be in a single line .
4

With innerHTML, the actual DOM gets updated everytime you make a change. So you can't reliably make piecemeal changes like you're doing. Create a variable like var html and save all your HTML updates into it, then set element.innerHTML = html.

var newdiv = document.createElement('div');
var html = "";
var text="TEXT";
var n=0;
html += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 0;

var options = '';
for (var j = 1; j < 5; j++) {
 var val = "marwa" + j;
 if (val) {
    m++;
    options += " <option value="+j+"> " + val + "</option>";
 }
}
html += "<select name='single' id='single'>";
html += " "+options + " </select> ";
newdiv.innerHTML = html;

document.getElementById('results').appendChild(newdiv);​

1 Comment

+1 for suggesting using a variable and commit changes just once. My answer would be the same.
1
var newdiv = document.createElement('div');
var text="TEXT";
var n=1;
newdiv.innerHTML += "<br> Question " + (n) + " : " + text + " ? <br><br>";
var m = 1;

var options = '';
for (var j = 0; j <= 5; j++) {
     var val = "marwa" + j;
if (val) {
        m++;
        options += " <option value="+j+"> " + val + "</option>";
         }
    }
newdiv.innerHTML += "<select name='single' id='single'  "+options + " </select> ";

document.getElementById('results').appendChild(newdiv);​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.