Robert
Robert

Reputation: 39

Javascript for loop to add "n" number of option elments?

I have a number that is generated dynamically, and I would like to add this number of option elements to a select. I am thinking a for loop would be the best way to do this. Say my variable containing the number is var number. thanks for any help.

My starting HTML is:

<select id="test">
    
</select>

Using Javascript, I need something like this:

function selectOne() {
    var select = document.getElementById('test');
    // for loop goes here?
    //   e.select[0] = new Option(number);  // do this n times with value also equaling number
}

So my resulting HTML needs to look like this, if the number = 6:

<select id="test">  
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

Upvotes: 1

Views: 11328

Answers (2)

SReject
SReject

Reputation: 3936

This should create your Options. And is backwards compatible for quite-a-many browsers supporting javascript

function selectOne() {
    for (var selectEle = document.getElementById("test"), i = 1, o; i <= 6;  i += 1) {
        o = document.createElement("option");
        o.value = i;
        o.appendChild(document.createTextNode(i));
        selectEle.appendChild(o);

        /*
        // As pointed out in the comments it can be done as such:
        o = document.createElement("option");
        o.value = o.text = i;
        selectEle.appendChild(o);
        */
    }
}

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382160

This builds n options :

function selectOne() {
  var select = document.getElementById('test');
  for (var i=0; i<n; i++) {
     select.options[select.options.length] = new Option(i+1, i);
  } 
}

Demonstration

Upvotes: 4

Related Questions