how to find out which option is selected in a <select> and how to escape the name?
i have got this HTML code:
<select name="audience[8787330733][value]">
<option value=""></option>
<option value="80">Everyone</option>
<option selected="1" value="50">Friends of Friends</option>
<option value="40">Friends</option>
</select>
now i want to find out wh开发者_运维知识库ich of these options are selected.
i tried
$('select[name="audience[8787330733][value]"] option:selected').text();
but this does not work :( I think I didn't escaped the name in the right way...
Thank you for your answers!!! :)
You should reference elements by id as it's the fastest selector as in @Arif's answer.
If it is not possible for you to change the html you can try:
(escaping special symbols in jQuery selectors can be achieved by using double backslashes)
$('select[name=audience\\[8787330733\\]\\[value\\]] option:selected').text()
http://jsfiddle.net/TfThK/ - tested on your example.
Use id in select:
<select id="audience" name="audience[8787330733][value]">
<option value=""></option>
<option value="80">Everyone</option>
<option selected="1" value="50">Friends of Friends</option>
<option value="40">Friends</option>
</select>
Then try with the following code:
$('#audience').val();
or
$('#audience selected:option').val();
And if you want to get selected text then just replace
val()
with
text()
Try this
<select name="audience[8787330733][value]" class="className">
<option value=""></option>
<option value="80">Everyone</option>
<option selected="1" value="50">Friends of Friends</option>
<option value="40">Friends</option>
</select>
Jquery If you want to get selected text
$('.className option:selected').text();
If you want to get selected value
$('.className option:selected').val();
Check this DEMO
精彩评论