Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get value a select elements option with jQuery?

Tags:

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_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.

like image 737
Peter Avatar asked Apr 08 '26 13:04

Peter


1 Answers

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.

like image 94
Karasutengu Avatar answered Apr 11 '26 03:04

Karasutengu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!