View Full Version : Using getElementById with a SELECT
Feb 1, 2004, 02:43 AM
I am trying to use document.getElementById to grab the currently selected OPTION within a SELECT list. Problem is, I don't really know what attribute to use for this - it isn't "value" like it would be for, say, grabbing what's in a text box.
Feb 1, 2004, 02:01 PM
Feb 1, 2004, 03:05 PM
It's not a dumb question. I could have explained that more clearly. I think I put in all sorts of detail without really saying what I was trying to communicate! :D Let's see if I can do a better job of it the second time around.
Here's the deal. I have, in my HTML code, a form that has some code like this (I'm simplifying it for clarity):
<input type="text" id="text1" value="w00t!">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
tvalue1 = document.getElementById("text1").value
But it doesn't seem to work the same way if I want to get the value of the currently selected option in the select dropdown list.
The reason I need to do this is: I have a form that has a single set of input fields - a text box and a select dropdown list. But some users want to have the option of entering more info without having to use the form, reload it, use it again, etc. In other words, they want the option of clicking a button that adds another text box + dropdown list pair (and another, and another, and ...).
I can do that by rewriting the "innerHTML" data for the "changeable_stuff" div element.
document.getElementById("changeable_stuff") .innerHTML = "New bunch of HTML for the form"
But when you do this, any data that was already entered in the form gets lost unless you store it first (and then put it back afterward). So I need to grab the value for both the text box and the dropdown list beforehand.
I know it's not a trivial question, but the forum here seems to have a wide range of users so I'm hoping someone will be able to point me in the right direction. I believe I have a workaround for it, but it's kinda clunky so I'd like to learn if there's a better way.
Feb 1, 2004, 06:02 PM
Well, I set up a very simple test page and did some testing (what else?). Looks like I was mistaken - I should still be able to grab 'value'. My problem must be elsewhere.
Just in case anyone in the future is searching for this same answer, here are a couple useful items in this instance:
document.getElementById("text1").value will provide the value of the currently selected option - that is, if the option specified has 'value="xxxx"', it returns "xxxx".
document.getElementById("text1").selectedIndex will return the number of the selected option. So if you've currently picked the fourth option from the dropdown, it'll return "4". Given how you have to script around to preselect an option in a dropdown, this is probably the more useful attribute of the two I've listed.
Feb 2, 2004, 12:07 AM