如何使用jQuery获得下拉框的选定值? 我试着用

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

and

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

但两者都返回空字符串。


当前回答

您是否为选择元素提供了id?

<select id='dropDownId'> ...

你的第一句话应该有用!

其他回答

这样就可以了

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

我知道这是一个非常老的帖子,我可能应该为这个可怜的复活而被鞭打,但我想我将分享几个非常有用的小JS片段,我在我的武器库中使用每个应用程序…

如果输入:

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

是老了,尝试添加这些小松脆饼到你的全局*.js文件:

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

然后写soval("#selector");或sotext(“#选择器”);相反!如果将两者结合并返回一个包含值和文本的对象,那就更好了!

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

它为我节省了大量宝贵的时间,尤其是在表单较多的应用程序上!

试试这个,它得到的值:

(“选择# myField美元)。找到选项:selected’)。瓦尔();

试试这个

$("#yourDropdown option:selected").text();

您可以通过使用以下代码来实现这一点。

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

如果您想从选择列表的选项中获取所选值。这样就可以了。

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