2012-03-23 69 views
2

選項的值我有以下幾點:獲得通過文本

<select name="dayRange" class="styled"> 
    <option value="0">All day</option> 
    <option value="1">Morning and day (8:00 - 18:00)</option> 
    <option value="2">Evening(18:00 - 6:00)</option> 
</select> 

我怎樣才能得到value特定的文本?
例如:返回valueAll Day。 謝謝。

回答

10
var text = "All day"; 

var value = $("option").filter(function() { 
    return $(this).text() === text; 
}).first().attr("value"); 
+0

酷。十分感謝。 – user1254282 2012-03-23 10:21:23

1

我想你需要瀏覽它們。

$("select.styled option").each(function(a,b) { 
    if ($(this).html() == "All day") { 
     return $(this).val(); 
    } 
}); 

或使用.filter()

$("select.styled option").filter(function() { 
    return $(this).html() == "All day"; 
}).val(); 
3

另一個解決方案是通過選擇項目這樣

$('select[name="dayRange"] > option:contains("All Day")').val() 

您可以添加到這個函數和替換 「全天」你的函數參數。

編輯(調用.VAL()如果你選擇不爲空之前只檢查):

最終的功能是:

getDayRangeValue = function(rangeName) { 
    // will return undefined if range doesn't exist. 
    return $('select[name="dayRange"] > option:contains("' + rangeName + '")').val(); 
} 
+0

這確實是最好的解決方案!謝謝@Mordhak – dav 2012-12-14 13:12:59