I have a simple question. I have a select list like this:
var myarray = ["one", "two", "three"];
var container = document.createElement("select");
for (var i = 0; i < myarray.length; i++) {
var element = document.createElement("option");
var textlabel = document.createTextNode(myarray[i]);
if (element.nodeValue == "two") {
element.selected = true;
}
element.appendChild(textlabel);
container.appendChild(element);
}
document.body.appendChild(container);
I have two questions about it:
1) I am pretty sure that the element that should be selected right now is “two”… isn’t it?
2) Since the option elements are being created dinamically inside a loop (there are no three different option variables for me to play with, but just one that gets renewed as the loop goes forward), how do I reference the selected one for future uses?
For example, imagine that later on I get user input, and according to that input I want that this list has as a selected item, “three”.
Thank you for any help! Here is the fiddle if you want to use it…
No, it’s not: you check element.nodeValue, while in fact you should’ve been checking
textLabel‘s one – or just the content itself:See,
<select>elements has two useful properties:options(which contains all the options in it, and is updated dynamically) andselectedIndex. You can combine them to get the selected option:But if what you want is to know the value of selected element, that’s even easier – with
container.value.That’s piece of cake if you know the position of the option that corresponds to this: just use selectedIndex property again: