tags:

views:

49

answers:

2

Hi,

I have the following HTML:

<div style="width: 143px; height: 125px; overflow: scroll;"><select size="20" style="min-width: 200px;" name="ctl00$ctl04$ctl00$ctl00$SelectResult" id="ctl00_m_g_ctl00_ctl00_SelectResult" multiple="multiple" title="selected values" onchange="GipSelectResultItems(ctl00_m_g_ctl00_MultiLookupPicker_m);" ondblclick="GipRemoveSelectedItems(ctl00_m_g_ctl00_ctl04_ctl00_ctl00_MultiLookupPicker_m); return false" onkeydown="GipHandleHScroll(event)">
                <option value="14">BMT</option></select></div>

How do I get the text in the option no matter of what the value is? I thought I could do something like:

 var test = $('#ctl00_m_g_ctl00_ctl00_SelectResult selected:option').text(); 

but it gives me "undefined".

Any ideas?

Update: I don't want to get a javascript error if the select doesn't have an option.

+5  A: 

Hi. Please try this one:

$('#ctl00_m_g_ctl00_ctl00_SelectResult option:selected').text();

Update. To avoid the javascript error, you could use something like:

var test = null;
var opt = $('#ctl00_m_g_ctl00_ctl00_SelectResult option:selected');

if (opt.length > 0){
  test = opt.text();
}

And after that just check if test is null or not.

Karasutengu
+1 this is the way to go, entirely. `option:selected` returns all the selected options, but if there are more than one, you probably want to iterate them to get some more meaningful representation than what you'll get from `.text()`. that's entirely up to what result you *want* when there are more than 1 selected item, tho.
David Hedlund
In this case I just want to check if the select has any option at all. The user populates it by adding options from another list and during validation of the form I don't want it to be empty.
Peter
@Peter: oh, but that's not what the code does at all. the above explicitly checks for *selected* items. it might be more straightforward for you to simply check if `('#ctl00_... option').length > 0`
David Hedlund
Yes, David is right. By removing the ":selected" portion it will check all the elements, not only the selected ones.
Karasutengu
A: 

There is often a confusion between these functions

.text(); //get the text of an HTML element
.val();  //get the value of an HTML Input
.html(); //get the HTML inside the html element.

You want .text() in this instance.

James Wiseman
`.val();` also gets the values of `select` and `textarea`.
David Hedlund