2

I am trying to add option in select tag but its not working.

container.appendChild(document.createTextNode("location"));
var select = document.createElement("select");
var option1 = document.createElement("option");
option1.text = "mumbai";
option1.value = "mumbai";
container.appendChild(option1);
container.appendChild(select);
4
  • 2
    You're adding the option element to whatever container contains and not the select Commented Dec 17, 2016 at 11:08
  • i want to add dymiic select option Commented Dec 17, 2016 at 11:10
  • dynamic by add buttun Commented Dec 17, 2016 at 11:11
  • use SelectElement.add Commented Dec 17, 2016 at 11:21

3 Answers 3

4

You're adding the option to the container and not to the select. So change container.appendChild(option1); to select.appendChild(option1);:

var container = document.getElementById('elem')
container.appendChild(document.createTextNode("location"));
var select = document.createElement("select");
container.appendChild(select);
var counter = 0;
document.getElementById("btn").addEventListener("click", function() {
  counter++;
  var option1 = document.createElement("option");
  option1.text = "mumbai" + counter;
  option1.value = "mumbai" + counter;
  select.appendChild(option1);
});
<div id='elem'>

</div>
<button name='btn' id='btn'>Add</button>

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

Comments

2

An alternate way is to add to options list of select.

var select = document.getElementById('select');
var options = select.options;
options[options.length] = new Option("Option 1", "1");
options[options.length] = new Option("Option 2", "2");
<select id="select"></select>


HTMLSelectElement.add() is another possibility.

var sel = document.createElement("select");
var opt1 = document.createElement("option");
var opt2 = document.createElement("option");

opt1.value = "1";
opt1.text = "Option: Value 1";

opt2.value = "2";
opt2.text = "Option: Value 2";

sel.add(opt1, null);
sel.add(opt2, null);

document.body.appendChild(sel);

Comments

1

You have add option1 element to select element instead of container element.

Change line:

container.appendChild(option1);

To:

select.appendChild(option1);

2 Comments

Your eplanation says something but your code says something else.
Why? Its about change element "container" to "select". In code example I just change this and comment this line.

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.