Get a List of the Selected Values in a ListBox

偶尔善良 提交于 2019-12-07 01:37:11

问题


There's already a question with a ton of votes for getting the selected value from a dropdown using jQuery here.

That answer almost works for a listbox, but if multiple values are selected, the result is a single string with all the values concatenated. This is not useful. I need a collection (list, array, whatever) of the text values for each selected option.

At the moment I'm thinking I'll use most of the answer from that other question, but without the .text() at the end, and then iterate through the matches. Better ideas?


回答1:


You can take multiple selected text by iterating loop as mentioned below.

$('#f1').click(function(){    
   var rr = []; 
   $('.selectpicker :selected').each(function(i, selected){ 
        rr[i] = $(selected).text(); 
    });
    alert(rr);
});

OR if you want to using it's value then simply write.

$('.selectpicker').val();

Demo




回答2:


You can use as below :

var selectedVal= []; 
$('#multiple :selected').each(function(i, selected){ 
   selectedVal[i] = $(selected).text(); 
   alert(selectedVal[i]);
});

Here is Tutorial and example



来源:https://stackoverflow.com/questions/28424067/get-a-list-of-the-selected-values-in-a-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!