views:

47

answers:

2

This things works perfectly

<select name="selectbox" onchange="alert(this.value)>

But I want to select the text. I tried in this way

<select name="selectbox" onchange="alert(this.text)>

It shows undefined. I found how to use dom to get text. But I want to do this in this way, I means like using just this.value.

+1  A: 

In order to get the value of the selected item you can do the following:

this.options[this.selectedIndex].text

Here the different options of the select are accessed, and the SelectedIndex is used to choose the selected one, then its text is being accessed.

Read more about the select DOM here.

Oded
`this.options[this.selectedIndex].value` is exactly the same as `this.value`, sorry.
Delan Azabani
@Delan Azabani - answer updated.
Oded
When I use this.options[this.SelectedIndex].text error console says -Error: this.options[this.SelectedIndex] is undefined
SHAKTI
SHAKTI: That's because it's `selectedIndex` rather than `SelectedIndex`.
Tim Down
+1  A: 
this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

Delan Azabani
Thanks This works.
SHAKTI
I don't like it. While I'm sure it does work on current browsers, it's an odd mixture of DOM element-based code and old-style form manipulation code. `options` returns a list of `Option` objects, which I'm not sure are specified anywhere to be the same thing as `<option>` elements. Better to use the time-honoured `text` property of the selected `Option`, which is guaranteed to work.
Tim Down
Tim, `Option` objects are the same as `HTMLOptionElement` objects. If you object to using `options`, you could alternatively use `children` or `childNodes` instead (can't remember exactly which one; I think that they both work)
Delan Azabani
I think you misunderstand slightly: I'm fully in favour of using `options`, but `Option` objects predate `HTMLOptionElement` objects and there's no specification I've seen that mandates that `Option` and `HTMLOptionElement` must be the same thing, even though they may well be in most browsers that support both. My point is that it would be safer not to mix the two styles. So, I'd prefer `this.options[this.selectedIndex].text` or a node-based thing based on `selectedIndex`, which is complicated by need to filter out whitespace text nodes in IE.
Tim Down
That's a very good point. Just out of curiosity, if you have non-text nodes inside the option nodes, does `text` return the `innerHTML`, or just all the text nodes combined?
Delan Azabani