jQuery get selected option value (not the text, but the attribute 'value')

随声附和 提交于 2019-11-27 06:13:10

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

$('select[name=selector]').val()
David Torres

I just wanted to share my experience

For me,

$('#selectorId').val()

returned null.

I had to use

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

$('select').change(function() {
    console.log($(this).val())
});​

jsFiddle example

.val() will get the value.

You need to add an id to your select. Then:
$('#selectorID').val()

you can use jquery as follows

SCRIPT

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

FIDDLE is here

Payal Mittal

Try this:

$(document).ready(function(){
    var data= $('select').find('option:selected').val();
});

or

var data= $('select').find('option:selected').text();

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();

One of my options didn't have a value: <option>-----</option>. I was trying to use if (!$(this).val()) { .. } but I was getting strange results. Turns out if you don't have a value attribute on your <option> element, it returns the text inside of it instead of an empty string. If you don't want val() to return anything for your option, make sure to add value="".

Look at the example:

    <select class="element select small" id="account_name" name="account_name"> 

        <option value="" selected="selected">Please Select</option>           
        <option value="paypal" >Paypal</option>
        <option value="webmoney" >Webmoney</option>

    </select>

 <script type="text/javascript">

        $(document).ready(function(){ 
             $('#account_name').change(function(){
               alert($(this).val());                                                          
             });
        });
 </script>
Saddam Khan
$('#selectorID').val();

OR

$('select[name=selector]').val();

OR

$('.class_nam').val();

this code work very well for me: this return the value of selected option. $('#select_id').find('option:selected').val();

 $(document ).ready(function() {
    $('select[name=selectorname]').change(function() { 
     alert($(this).val());});
 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!