Rork.nl - Articles
JavaScript: change the contents of a select input
It has been a long time since I used any javascript unless for some simple pop-up windows but I was working on a on-line library where you can filter the books on a catagory and on a genre. Not all genres are used for each catagory so when you select a catagory it would be quite usefull when only appropriate genres are shown.6
JavaScript 1.1 and higher support changing the contents of a select input and it took me a little time to find out how to do this. A function is called with an onchange tag in the selector's definition. This function will empty the second selector and fill it again depending on the selected choise.
You have to name your form and both select inputs, then you can access them with:
document.formName.selectName.<option>
where the content of the select input is contained in
document.formName.selectName.options[]
You can empty the select input by setting it's length to 0:
document.formName.selectName.options.length = 0;
Then add a new option for each option you want:
document.formName.selectName.option[0] = new Option("name", "value"); document.formName.selectName.option[1] = new Option("name", "value"); document.formName.selectName.option[2] = new Option("name", "value"); ...
You can view the code I use here