如何从jQuery的下拉列表中获取所选文本(而不是所选值)?
当前回答
$(“#DropDownID”).val()将给出选定的索引值。
其他回答
这里张贴的答案,例如,
$('#yourdropdownid option:selected').text();
对我来说没用,但这样做了:
$('#yourdropdownid').find('option:selected').text();
它可能是jQuery的旧版本。
如果变量中已经有下拉列表,这对我很有用:
$("option:selected", myVar).text()
这个问题的其他答案对我有帮助,但最终jQuery论坛线程$(this+“option:selected”).attr(“rel”)选项在IE中不起作用帮助最大。
更新:修复了上述链接
这对我有用
$("#dropdownid").change(function() {
alert($(this).find("option:selected").text());
});
如果元素是动态创建的
$(document).on("change", "#dropdownid", function() {
alert($(this).find("option:selected").text());
});
只需添加以下行
$(this).prop('selected', true);
将.att替换为.prop,它适用于所有浏览器。
使用此
const select = document.getElementById("yourSelectId");
const selectedIndex = select.selectedIndex;
const selectedValue = select.value;
const selectedText = select.options[selectedIndex].text;
然后在selectedValue和selectedText中获取所选值和文本。