1

Here is my code:

<!doctype html>

<html>
<head>
    <meta charset="utf-8">
    <title>Date Picker</title>
</head>
<body>
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<select id="demo">
</select>
<p id="demo"></p>
<script>
function myFunction()
{
    var i;
    for (i=1;i<=5;i++){
      document.getElementById("demo").innerHTML="<option value="+i+">"+i+"</option>";
    }
}
</script>
</body>
</html>

all I want is when I press the button dropdown box will generate an option like this:

<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>

but I get only this code

<option value="5">5</option>

it only show 5 on the option. Please help.. Thank you

2 Answers 2

7

[Edit 2022] Old answer, modernized a bit and added a snippet (ES)

You are overwriting the contents of 'demo' in every iteration. It's better to use DOM methods to add options to a select, in this case new Option([arguments]):

function myFunction(selector) {
  for (let i = 1; i <= 5; i++) {
    selector.options[i] = new Option(i + 1,i + 1);
  }
}
//usage:
myFunction(document.getElementById("demo"));

By the way: check your HTML. The id of elements should be unique. Using your HTML, how can your script know which element is meant with document.getElementById("demo")?

Below a demo snippet for another (ES) way of looping. It uses event delegation for handling the button click.

document.addEventListener(`click`, handle);
const loop = (n, lambda) => [...Array(n)].forEach( lambda );

const setSelectOptions = forSelector => [...Array(5)].forEach( (_, i) => 
  forSelector.options[i] = new Option(`option ${i + 1}`, i + 1) );
    
setSelectOptions(document.querySelector(`#demo`));

function handle(evt) {
  if (evt.target.id === `demoLoop`) {
    document.querySelector(`#loopDemo`).textContent += 
      [...Array(5)].map( (_, i) => `${i+1} Hello!`).join(`\n`) + `\n`;
  }
}
<select id="demo"></select>
<p>
  Click the button to loop through a 
  block of code five times.</p>
<button id="demoLoop">Try it</button>
<pre id="loopDemo"></pre>

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

Comments

6

Add element to select like this will work for you

var select = document.getElementById("demo");  

var i=0;
 for(i=1;i<=5;i++){  
     select.options[select.options.length] = new Option(i,i);  

} 

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.