How to Fill a Combobox with JavaScript
Sometimes in web programming you'll need to change webpages after they've already been loaded. Luckily, JavaScript makes this simple. If you need to add options to a combo box (called a select box in HTML) after the page loads, to enable a cascading drop-down in which each selection affects what the user sees in the next list, for example, then a few simple lines of JavaScript will do the job.
Instructions
-
-
1
Get the select box from the page by using the built-in getElementById:
var selectBox = document.getElementById('selectBoxId'); -
2
Create the new option using the built-in createElement function:
var newOption = document.createElement("option");
option.text = "Option Text";
option.value = "Option Value"; -
-
3
Add the new option to your select box:
selectBox.options.add(option);
-
1
Tips & Warnings
If this code doesn't work with your browser, consider using a JavaScript framework such as jQuery or Prototype, which handle browser-compatibility issues automatically.
References
Resources
- Photo Credit computer image by blaine stiger from Fotolia.com