Get selected value of a dropdown's item using

2018-12-31 08:08发布

How can I get the selected value of a dropdown box using jQuery?
I tried using

var value = $('#dropDownId').val();

and

var value = $('select#dropDownId option:selected').val();

but both return an empty string.

标签: jquery
29条回答
泛滥B
2楼-- · 2018-12-31 09:09

I know this is a terribly old post and I should probably be flogged for this pitiful resurrection, but I thought I would share a couple of VERY helpful little JS snippets that I use throughout every application in my arsenal...

If typing out:

$("#selector option:selected").val() // or
$("#selector option:selected").text()

is getting old, try adding these little crumpets to your global *.js file:

function soval(a) {
    return $('option:selected', a).val();
}
function sotext(a) {
    return $('option:selected', a).text();
}

and just write soval("#selector"); or sotext("#selector"); instead! Get even fancier by combining the two and returning an object containing both the value and the text!

function so(a) {
    my.value = $('option:selected', a).val();
    my.text  = $('option:selected', a).text();
    return my;
}

It saves me a ton of precious time, especially on form-heavy applications!

查看更多
墨雨无痕
3楼-- · 2018-12-31 09:09

The id that got generated for your drop down control in the html will be dynamic one. So use the complete id $('ct100_<Your control id>').val(). It will work.

查看更多
宁负流年不负卿
4楼-- · 2018-12-31 09:09

use either of these codes

$('#dropDownId :selected').text();

OR

$('#dropDownId').text();
查看更多
梦醉为红颜
5楼-- · 2018-12-31 09:10

use

$('#dropDownId').find('option:selected').val()

This should work :)

查看更多
谁念西风独自凉
6楼-- · 2018-12-31 09:12

You can do this by using following code.

$('#dropDownId').val();

If you want to get the selected value from the select list`s options. This will do the trick.

$('#dropDownId option:selected').text();
查看更多
登录 后发表回答