如何使用jQuery获得下拉框的选定值? 我试着用
var value = $('#dropDownId').val();
and
var value = $('select#dropDownId option:selected').val();
但两者都返回空字符串。
如何使用jQuery获得下拉框的选定值? 我试着用
var value = $('#dropDownId').val();
and
var value = $('select#dropDownId option:selected').val();
但两者都返回空字符串。
当前回答
试试这个jQuery,
$("#ddlid option:selected").text();
或者这个javascript,
var selID=document.getElementById("ddlid");
var text=selID.options[selID.selectedIndex].text;
如果你需要访问值而不是文本,那么尝试使用val()方法而不是text()。
看看下面的小提琴链接。
Demo1 | Demo2
其他回答
试试这个jQuery,
$("#ddlid option:selected").text();
或者这个javascript,
var selID=document.getElementById("ddlid");
var text=selID.options[selID.selectedIndex].text;
如果你需要访问值而不是文本,那么尝试使用val()方法而不是text()。
看看下面的小提琴链接。
Demo1 | Demo2
您可以通过使用以下代码来实现这一点。
$('#dropDownId').val();
如果您想从选择列表的选项中获取所选值。这样就可以了。
$('#dropDownId option:selected').text();
function fundrp(){ var text_value = $("#drpboxid option:selected").text(); console.log(text_value); var val_text = $("#drpboxid option:selected").val(); console.log(val_text); var value_text = $("#drpboxid option:selected").attr("value") ; console.log(value_text); var get_att_value = $("#drpboxid option:selected").attr("id") console.log(get_att_value); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <select id="drpboxid"> <option id="1_one" value="one">one</option> <option id="2_two" value="two">two</option> <option id="3_three" value="three">three</option> </select> <button id="btndrp" onclick="fundrp()">Tracking Report1234</button>
我知道这是一个非常老的帖子,我可能应该为这个可怜的复活而被鞭打,但我想我将分享几个非常有用的小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;
}
它为我节省了大量宝贵的时间,尤其是在表单较多的应用程序上!
$("#dropDownId").val('2');
var SelectedValue= $("#dropDownId option:selected").text();
$(".ParentClass .select-value").html(SelectedValue);
<p class="inline-large-label button-height ParentClass" >
<label for="large-label-2" class="label">Country <span style="color: Red;">*</span><small></small></label>
<asp:DropDownList runat="server" ID="dropDownId " CssClass="select" Width="200px">
</asp:DropDownList>
</p>