2013-02-20 65 views
7

我有GET問題多所有選擇的選項中選擇如何獲得所有選擇的選項的文本形式多選擇使用JavaScript

<select multiple="" title="" class="" id="fm_delivery_or_collection" name="fm_fields[fm_delivery_or_collection][]"> 
    <option value="90">Delivery or Collection1</option> 
    <option value="91">Delivery or Collection2</option> 
    <option value="92">Delivery or Collection3</option> 
</select> 

貝婁是我的代碼和它返回我只有第一個選擇的選項

var select = form.find('select') 

for (var i = 0; i < select.length; i++) 
     { 
      var s_id = jQuery(select[i]).attr('id'); 
      var str="",i; 

      var e = document.getElementById(s_id); 
      var strUser = e.options[e.selectedIndex].text; 

      var name = jQuery(select[i]).attr('name') 
      var str1 = jQuery(select[i]).attr('id').replace("fm_"," ") 
      requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>"; 
     } 

所以請建議我如何獲取所有選定的選項文本和我犯的錯誤?

+0

的價值'選擇multiple'(或'選擇[select.selectedIndex]')是一個數組... – Teemu 2013-02-20 05:15:16

+0

答案過於複雜。您可以使用.map()獲取所有選定的選項文本。 $(「select:selected」)。map(function(i,element){return jQuery(element).text();})。get();' – 2018-01-30 10:08:05

回答

23

您的評論please suggest me how can i get all selected option textSo you can try this

$("#fm_delivery_or_collection option:selected").each(function() { 
    var $this = $(this); 
    if ($this.length) { 
    var selText = $this.text(); 
    console.log(selText); 
    } 
}); 
2

嘗試用這種

$("#fm_delivery_or_collection option").each(function(){ 
    if($(this).attr('selected') == 'selected') 
    { 
     var name = $("#fm_delivery_or_collection").attr('name') 
     var str1 = $("#fm_delivery_or_collection").attr('id').replace("fm_"," ") 
     requestString += "<b>"+str1.replace(/_/g," ")+"</b>" + ':' +strUser+"<br>"; 
    } 
}) 
+0

這是否正常工作.. ?? – Gautam3164 2013-02-20 05:19:58

+0

你好......... @ user123是否正在工作......你需要回復 – Gautam3164 2013-02-20 05:26:50

+0

好吧Gautam爲什麼這樣會起作用? – Jai 2013-02-20 05:35:27

11
// Return an array of the selected opion values 
// select is an HTML select element 
function GetSelectValues(select) { 
    var result = []; 
    var options = select && select.options; 
    var opt; 

    for (var i=0, iLen=options.length; i<iLen; i++) { 
    opt = options[i]; 

    if (opt.selected) { 
     result.push(opt.value || opt.text); 
    } 
    } 
    return result; 
} 

通過這個功能您的選擇框像..

var selectBox = document.getElementsById('fm_delivery_or_collection'); 
alert(GetSelectValues(selectBox)); 

它將返回選定值

的陣列通過使用jQuery

$('select#fm_delivery_or_collection').val() 

val函數調用select將返回一個數組,如果它的倍數。

0
$("#id :selected").each(function (i,sel) { 
    alert($(sel).text()); 
}); 

希望它有助於..

0

try this link

$("#selection option:selected").each(function() { 
    var $this = $(this); 
    if ($this.length) { 
    var selText = $this.text(); 
    console.log(selText); 
    $('#selected').append(selText+', '); 
    } 
}); 
相關問題