I am trying to create and populate a HTML select and option tags using JavaScript. The text to be used within the option statements comes from an XML file. I am able to parse the XML file problem free yet I am stuck when it comes to populating the new select box. Despite any changes I have attempted with this code it does not work. Does anyone have any insight on what I am doing wrong here?
My XML file:
<londonStreets>
<street>Clarence Street</street>
<street>Dundas Street</street>
<street>King Street</street>
<street>Queens Avenue</street>
<street>Richmond Street</street>
<street>Waterloo Street</street>
<street>Wellington Street</street>
<street>York Street</street>
</londonStreets>
My JavaScript that I figured would create the new select box:
var streetSelector=document.createElement('select');
streetSelector.setAttribute('id', 'street');
for (i=0;i<x.length;i++)
{
var option=document.createElement('option');
option.setAttribute('value', x[i].childNodes[0].nodeValue);
option.appendChild(document.createTextNode(x[i].childNodes[0].nodeValue));
streetSelector.appendChild(option);
}
-
1Good for you, using regular JavaScript :)oooyaya– oooyaya2013年07月01日 20:31:56 +00:00Commented Jul 1, 2013 at 20:31
-
Did you append the streetSelector to some HTML element (body, div, etc?)oooyaya– oooyaya2013年07月01日 20:33:22 +00:00Commented Jul 1, 2013 at 20:33
2 Answers 2
You have not appended streetSelector to your DOM. See this JS fiddle:
document.getElementById("content").appendChild(streetSelector);
Comments
without seeing what x is exactly, here is a simplified options populator routine:
var streetSelector=document.createElement('select');
streetSelector.id='street';
for (i=0;i<x.length;i++){
streetSelector.appendChild(new Option( x[i].childNodes[0].nodeValue));
}