That answer above it a little tricky, so here's what i did:
<script>
function test() {
var x = document.getElementById('selectfield').selectedIndex;
alert(x);
}
</script>
and the HTML:
<select id="selectfield" onChange="test()">
<option value="0"></option>
<option value="1"> something </option>
<option value="2"> something different </option>
<option value="3"> complete other text </option>
</select>
Notice a few differences here. First, in the javascript, a DOM command called '.selectedIndex
' which gets the option selected in the box.
Now for what I did to the HTML, Notice a couple of things. First, you have an event Handler called onChange
which calls the function i created called test()
. I also added a blank option so that if someone wanted to choose the first one they could, and not have to click the second option and then the first to get that particular choice. Honestly, those value=""
attributes are not necessary now.
If you run the code, you might notice that instead of returning text, it returns a number. "A number?" you might ask, "I wanted the text!". Here is a solution I have for you:
var option_Array = [];
option_Array[0] = "";
option_Array[1] = "something";
option_Array[2] = "something different";
option_Array[3] = "complete other text";
Suppose you had an array of the options, now all you would have to do is use the variable x
as the index number of the array like so:
option = option_Array[x];
Now the new variable option is equal to whatever item you clicked!
I hope this fully answers your question. I would appreciate any feedback on this answer, as it is 1:10 AM and I'm not perfect.
Just as a side note, it might be a good idea to put a parseInt()
around
var x = parseInt(document.getElementById('selectfield').selectedIndex);
just in case it returns x
as a string instead of a real integer.