Handling of select-list items in javascript
How to get a selected value from <select> using DOM
In the piece of javascript code below, you've got in the "value" variable the actual selected value of the <select> with id "idOfSelectInput"
var sel = document.getElementById("idOfSelectInput");
var value = sel.options[sel.selectedIndex].value;
... or you can use "modern" way that support all modern browsers, so no worries. It's much simpler:
var value = document.getElementById("idOfSelectInput").value;
How to get a text of the selected item in <select>
We can use the code above, and change it just a little bit:
var sel = document.getElementById("idOfSelectInput");
var text_value = sel.options[sel.selectedIndex].text;
Add item to <select> using Javascript
In the code below we add one item using simple javascript:
var sel = document.getElementById("idOfSelectInput");
sel.options.add(new Option('text of item', 'value of item'));
Delete item from <select> using Javascript
Finally, we will delete one or more selected items from the list. It depends if you have created your <select> with attribute "multiple". Code for both types (single or multi) follows:
// deleting one selected item
var sel = document.getElementById("idOfSelectInput");
sel.options[from.selectedIndex] = null;
// deleting multiple selected items
for (var i=(sel.options.length-1); i>=0; i--) {
var option=sel.options[i];
if (option.selected) sel.options[i] = null;
}
Change the size of <select> depending on number of items
Then you are using code mentioned above, that is, adding and deleting items in the list dynamically, you might want the <select> to change it's size appropriatelly. Here how it's done:
sel = document.getElementById('idOfSelectInput');
sel.setAttribute('size', sel.options.length);
sel.style.display='none';
sel.style.display='block';
Comments
There are no comments yet, you can be the first to add one...
Add your comment