2011-07-07 30 views
0

我多選下拉菜單中的工作下面提到jQuery來訪問多選擇下拉菜單

<select class="form-input name="hideLineItemColumns_quote" multiple="true" "> 
    <option selected="true" value="part_desc">Description</option> 
    <option selected="true" value="part_number">Product</option> 
    <option selected="true" value="costEa_line">Cost</option> 
</select> 

我要訪問值&文本的所有選擇的選項,並在進一步的邏輯中使用它們。我試過這樣做

var tempVar = jQuery("Select[@name='hideLineItemColumns_quote'] option:selected").text(); 
alert(tempVar[0]); 

而不是顯示「說明」,它顯示「D」。它將所有三個值組合在一個長字符串中。任何想法我做錯了什麼?

感謝, Nitesh

回答

1

tempVar是一個字符串。因此,您正在查看該字符串中的第一個字符,即D

此外,您還可以選擇所有選項。

也許這就是你的意思做的:

var tempVar = []; 
jQuery("Select[@name='hideLineItemColumns_quote'] option:selected").each(function() { 
        tempVar.push($(this).text()); 
}); 
alert(tempVar[0]); 
+0

有意義..但是不要回頭看一個字符串,它應該用三個值描述,產品和成本來回應一個數組。有沒有其他方法可以分別訪問所有選定的值? – Nitesh

+0

http://jsfiddle.net/efh4a/ – Joe

+0

上面的代碼工作正常,但頁面上還有其他Select標籤,邏輯拉第一個選擇標籤的第一個選定值,而不是我特別提到的標籤(@ name =' hideLineItemColumns_quote')。我是否需要指定其他內容? – Nitesh

0

您當前的查詢選擇所有三個option元素。當你在這個集合上調用.text()時,jQuery假定你想要所有三個組合的文本。

如果要單獨對付他們,你可以通過.each().map()迭代:

// with .each(): 
$("select[@name='hideLineItemColumns_quote'] option:selected").each(function(idx, el) { 
    console.log($(el).text()); 
}); 

// with .map(): 
var options_arr = $("select[@name='hideLineItemColumns_quote'] option:selected").map(function(idx, el) { 
    return $(el).text(); 
}); // => ['Description', 'Product', 'Cost'] 
console.log(options_arr); 

http://jsfiddle.net/hans/kCZDh/1/

+0

你知道爲什麼它顯示警告消息jsfiddle SS而不是描述。淨/ efh4a/2? – Nitesh

0

我已經打了它一下......

var tempVar = []; 
$('select[name="hideLineItemColumns_quote"] option:selected').each(function() { 
    var $option = $(this); 
    tempVar.push({ text: $option.text(), value: $option.attr('value') }); 
}); 
alert(tempVar[0].text); 

基本上,就像其他答案之一一樣,您可以製作一個列表中選定項目的數組。對於每個選定的項目,它會創建一個包含textvalue屬性的小對象,以便稍後可以更直觀地訪問它們。 (如在alert()一行);