[英]Getting the selected listValue of <s:select> in javascript
我正在使用struts標簽來顯示項目列表。
<s:select name="example" id="example" list="exampleList" listKey="exampleKey"
listValue="exampleValue" onchange="fun()"/>
現在我有一個javascript函數:
function fun()
{
var ex=document.getElementById("example");
alert(ex.value);
}
在這個函數中,我需要獲取所選項的listValue,但是當我使用上面的代碼時,它只是提醒我我選擇的listKey。 如何在javascript函數中獲取listValue而不是listKey?
$(document).ready(function() {
$('#reminderTypeID').change(function()
{
var ex = document.getElementById("reminderTypeID");
var selTex = ex[$('#reminderTypeID').val()].text;
var selVal = ex[$('#reminderTypeID').val()].value;
alert(ex[$('#reminderTypeID').val()].text);
});
});
試試這個(為我工作):
function fun()
{
var ex = document.getElementById("example");
alert(ex.getAttribute('listValue'));
}
編輯
添加小提琴: http : //jsfiddle.net/FranWahl/Ur6jT/2/
(不知道為什么它不適合你。在小提琴中它起作用。)
我遇到了同樣的問題,其他答案都沒有對我有用。 這是我發現的解決方案:
$(document).ready(function(){
$("#example").change(function(){
var options = document.getElementById("example").options;
var selectedIndex = document.getElementById("example").selectedIndex;
var selectedOptionText = options[selectedIndex].text;
var selectedOptionValue = options[selectedIndex].value;
console.log("Id of selected option is: " + selectedOptionValue);
console.log("Text of selected option is: " + selectedOptionText);
});
});
為了進一步理解這個問題,它有助於思考在處理JSP時創建HTML的內容。 <s:select>
將生成以下HTML:
<select id="example" name="example">
<option value="456">TextA</option>
...
</select>
在OP的示例代碼之后,“456”將從exampleKey
和exampleValue中的“TextA” exampleValue
。 exampleList
每個項都會有這樣的HTML <option>
。
請注意,在我的解決方案中,我使用了jQuery .change()
函數。 然而,我也嘗試了onchange="fun()"
的解決方案,正如OP所做的那樣,這也有效。
當我試圖取代document.getElementById("example")
以$("#example")
該解決方案沒有奏效。
閱讀<select>
選項selectedValue上的這個參考也很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.