[英]Jquery get selected text and value from selectlist optgroup
I need to get the selected text and value from the optGroup selectList below on the click of a button. 单击按钮,我需要从下面的optGroup selectList中获取选定的文本和值。 So something like? 像这样吗?
$("#addButton").click(function () {
var selected = ???
});
<select name="list">
<optgroup label="mammals">
<option>dog</option>
<option>cat</option>
<option>rabbit</option>
<option>horse</option>
</optgroup>
<optgroup label="reptiles">
<option>iguana</option>
<option>snake</option>
</optgroup>
</select>
You can use Attribute Equals
selector and val
method. 您可以使用Attribute Equals
选择器和val
方法。
$("#addButton").click(function() {
// var selected = $('select[name="list"] :selected');
var val = $('select[name="list"]').val();
});
val
method return the value of selected option
. val
方法返回选定option
的值。 However as your option tags have no value attributes, val
returns the text
of the selected option. 但是,由于您的选项标签没有值属性,因此val
返回所选选项的text
。
var value = $('select[name="list"] :selected').val();
var text = $('select[name="list"] :selected').text();
Provide an id to your select like "list", and you can try this 为您的选择提供一个ID(例如“列表”),您可以尝试执行此操作
$(function(){
$("#addButton").click(function () {
var select = $('select#list');
var selectedItem= select.find(':selected');
var selectedVal = select.val();
var selectedText = selectedItem.text();
var optgroupLabel = selectedItem.parent().prop('label');
alert("val =" + selectedVal + " text ="+ selectedText+" group =" + optgroupLabel );
});
});
Hope it will help. 希望它会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.