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

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

and

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

但两者都返回空字符串。


当前回答

对于单个select dom元素,获取当前选择的值:

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

获取当前选定的文本:

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

其他回答

我知道这是一个非常老的帖子,我可能应该为这个可怜的复活而被鞭打,但我想我将分享几个非常有用的小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;
}

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

对于单个select dom元素,获取当前选择的值:

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

获取当前选定的文本:

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

HTML:

<select class="form-control" id="SecondSelect">
       <option>5<option>
       <option>10<option>
       <option>20<option>
       <option>30<option>
</select>

JavaScript:

var value = $('#SecondSelect')[0].value;
$("select[id$=dropDownId]").val()

试试这个

$("#selector <b>></b> option:selected").val()

Or

$("#selector <b>></b> option:selected").text()

以上代码对我来说工作得很好