jQuery get selected option value (not the text, bu

2019-01-08 06:05发布

Okay, I have this code:

<select name="selector" id="selector">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>

And I'd like to get the value of the option selected. Example: 'Option 2' is selected, and the value of it is '2'. The '2' is the value I need to get and not 'Option 2'.

12条回答
等我变得足够好
2楼-- · 2019-01-08 06:25

you can use jquery as follows

SCRIPT

  $('#IDOfyourdropdown').change(function(){
    alert($(this).val());
  });

FIDDLE is here

查看更多
smile是对你的礼貌
3楼-- · 2019-01-08 06:26

Use .val to get the value of the selected option. See below,

$('select[name=selector]').val()
查看更多
smile是对你的礼貌
4楼-- · 2019-01-08 06:29

For a select like this

<select class="btn btn-info pull-right" id="list-name" style="width: auto;">
   <option id="0">CHOOSE AN OPTION</option>
   <option id="127">John Doe</option>
   <option id="129" selected>Jane Doe</option>

... you can get the id this way:

$('#list-name option:selected').attr('id');

Or you can use value instead, and get it the easy way...

<select class="btn btn-info pull-right" id="list-name" style="width: auto;">
   <option value="0">CHOOSE AN OPTION</option>
   <option value="127">John Doe</option>
   <option value="129" selected>Jane Doe</option>

like this:

$('#list-name').val();
查看更多
劳资没心,怎么记你
5楼-- · 2019-01-08 06:30
$('select').change(function() {
    console.log($(this).val())
});​

jsFiddle example

.val() will get the value.

查看更多
淡お忘
6楼-- · 2019-01-08 06:31
 $(document ).ready(function() {
    $('select[name=selectorname]').change(function() { 
     alert($(this).val());});
 });
查看更多
Evening l夕情丶
7楼-- · 2019-01-08 06:33

I just wanted to share my experience and my reputation is not enough to comment.

For me,

$('#selectorId').val()

returned null.

I had to use

$('#selectorId option:selected').val()

查看更多
登录 后发表回答