开发者

how to find out which option is selected in a <select> and how to escape the name?

开发者 https://www.devze.com 2023-04-12 11:33 出处:网络
i have got this HTML code: <select name=\"audience[8787330733][value]\"> <option value=\"\"></option>

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!!! :)


  1. You should reference elements by id as it's the fastest selector as in @Arif's answer.

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

0

精彩评论

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

关注公众号