[英]get the value of the select box by its attribute name
我有這個HTML
<select name="test">
<option value="" selected disabled>please select</option>
<option value="option1">option 1</option>
<option value="option2">option 2</option>
</select>
我試圖在選擇框中獲取當前所選選項的名為“值”內容的屬性的方式是(假設我已經選擇了選項1):
alert($("select[name='test'] option:selected", this).val());
但是它返回了我[object object]
。 有任何線索或想法嗎?
您只需要使用$("select[name='test']").val()
即可獲取所選值
$("select[name='test']").change(function() { alert($(this).val()); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select name="test"> <option value="" selected disabled>please select</option> <option value="option1">option 1</option> <option value="option2">option 2</option> </select>
選擇框的value屬性來自於select-multiple類型選擇框中的所選選項或第一個所選選項的value屬性。 因此,可以在JavaScript中按以下方式獲得selected選項的值:
// reference to 'category' select list in 'demoForm'
var sel = document.forms['demoForm'].elements['category'];
// value property of select list (from selected option)
var val = sel.value;
如果option元素不包含value屬性,則通常option元素的文本內容將為value屬性。 但是,在這種情況下,版本9之前的Internet Explorer將不提供該值。 如果您的選項元素不包含值屬性,並且您希望支持較舊的瀏覽器,則為達到最佳效果,請使用老式的方法來引用所選選項並訪問其文本屬性:
// access text property of selected option
var val = sel.options[sel.selectedIndex].text;
選擇列表的options屬性是其中包含的所有選項元素的節點列表。 選擇列表的selectedIndex屬性指定節點列表中所選選項的位置。 選項的text屬性是option元素的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.