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:06

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="".

查看更多
欢心
3楼-- · 2019-01-08 06:11

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

查看更多
对你真心纯属浪费
4楼-- · 2019-01-08 06:11
$('#selectorID').val();

OR

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

OR

$('.class_nam').val();
查看更多
等我变得足够好
5楼-- · 2019-01-08 06:13

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>
查看更多
Evening l夕情丶
6楼-- · 2019-01-08 06:20

Try this:

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

or

var data= $('select').find('option:selected').text();
查看更多
欢心
7楼-- · 2019-01-08 06:22

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

查看更多
登录 后发表回答