1

I'm trying to populate two dropdown menus in Javascript with numbers within the same for loop, but only one is ever populated (the last one)

for (var i=1; i<10; i++)
{
   var option = document.createElement("option");
   option.text = i; 
   option.value = i;        
   document.getElementById('first').options.add(option);
   document.getElementById('second').options.add(option);               
}

The element 'second' will get populated, where as the other will not, if I put 'second' above 'first' then 'first' will be populated.

How can I do this without using two for loops? I have tried passing the ID via a function to the loop and I still get the same output.

Thanks.

1 Answer 1

3

Little modification in your script

for (var i=1; i<10; i++)
{
   var option = document.createElement("option");
   option.text = i;
   option.value = i;   
   var newOption = option.cloneNode(true);   

   document.getElementById('first').options.add(option);
   document.getElementById('second').options.add(newOption);               
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm doing this in pure Javascript, i'm getting an error as .clone isn't actually a function?
@Elliott, my mistake I was using some library. Please refer update code with element.cloneNode(boolean) method

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.