How Do I Update Select Options From Javascript?
Javascript, Meta Tags February 17th, 2009I want to change the available list in the
<select> drop-down menu using a pre-defined array in javascript.
You can get access to the select controls options array which is used for accessing each element of the select. Through this collection you can add, remove, clear and modify existing options.
Do remember that when you go to add an option you have to create an option object first then supply it to the add method of the select control.
For example you can add a new option (or overwrite the first element) by using some code like…
// Get a reference to the select element named "selectname"
var select = document.getElementById( "selectname" );
// Create a new option item and then put it at the first spot
// in the list which has the index 0:
select.options[0] = new Option("text to put",0);
Another example is that you can clear the list (using the same reference as defined above…) by setting the options length to 0:
select.options.length = 0;