DeveloperLV
DeveloperLV

Reputation: 1781

Javascript - How to add 0 to 10 options to select element?

I am struggling to understand to why my code only creates this single option:

enter image description here

And not options from 0 to 10?

<div>
  <div id="SelectEl">

  </div>
</div>

<script>
  // Get el ID
  var el = document.getElementById('SelectEl');
  // Select element
  var selectList = document.createElement('select');
  // Option element
  var option = document.createElement('option');


  for (var i = 0; i < 11; i++) {
    // Add selectList element to div
    el.appendChild(selectList);
    // Add option to selectList
    selectList.appendChild(option);
    // Add text of a number 0 to 10
    option.text = [i]
  }
</script>

Upvotes: 0

Views: 136

Answers (2)

symlink
symlink

Reputation: 12218

Create the option element inside the loop, one for each iteration, and move the line where you append the selectList to the div to outside the loop:

const el = document.getElementById('SelectEl');
const selectList = document.createElement('select');
el.appendChild(selectList);

for (var i = 0; i < 11; i++) {
  var option = document.createElement('option');
  selectList.appendChild(option);
  option.text = [i]
}
<div id="SelectEl"></div>

Upvotes: 1

Taplar
Taplar

Reputation: 24965

<div>
    <div id="SelectEl">

    </div>
</div>

<script>
    // Get el ID
    var el = document.getElementById('SelectEl');
    // Select element
    var selectList = document.createElement('select');
    // Option element
    var option;


    for(var i = 0; i < 11; i++) {
        option = document.createElement('option');
        
        // Add text of a number 0 to 10
        option.text = [i]
        // Add option to selectList
        selectList.appendChild(option);
    }

    // Add selectList element to div
    el.appendChild(selectList);

</script>

  • Create a new option each iteration.
  • Append the whole select after the loop.

Upvotes: 2

Related Questions