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
19 comments so far...
17.02.2012 - 14:13qeqweqe
qwewqeq
02.04.2012 - 12:01AS
ERER
03.04.2012 - 12:54
10.04.2012 - 05:25
24.09.2012 - 09:03fd
alert("dfhf");
28.09.2012 - 11:31111
sss
28.09.2012 - 11:32Praveen
Nothing useful stuff out here.
28.09.2012 - 11:32Praveen
aaaaaaaaaaaaaaaaaa
11.12.2012 - 13:04
13.08.2013 - 09:08yt
rttr
13.09.2013 - 23:17Mohsin
thnks
25.09.2013 - 22:58Omar Silva
Excelente pagina. A mi si me sirvió mucho! Muchas gracias!
29.09.2013 - 18:05dsff
888yynf
29.09.2013 - 18:06hg
ma
08.01.2014 - 07:53
09.01.2014 - 05:26Gupta
WTF
18.07.2017 - 13:10spam
I am spam.
01.07.2021 - 23:17gg
ewrwr
01.07.2021 - 23:18gg
desfdsfds
Add your comment