开发者

get value a select elements option with jQuery?

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_SelectRes开发者_运维百科ult" 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜