9

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?

Community
  • 1
  • 1
DCShannon
  • 2,470
  • 4
  • 19
  • 32

2 Answers2

14

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

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
  • Yes, It will take all selected option from your dropdown. – Sadikhasan Feb 10 '15 at 04:30
  • Simply using .val gets me exactly what I want, as in this case the text and value for each option is the same – DCShannon Feb 10 '15 at 04:38
  • Sometimes .val() is returning an array of strings, which is what I want, and other times it is returning an array of DispHTMLOptionElement. Seems random. – DCShannon Feb 10 '15 at 04:50
  • Can you show me example where it is show `DispHTMLOptionElement` in your example? – Sadikhasan Feb 10 '15 at 04:53
  • Not consistently, no. Seems random. This code `var select = $( '#SelectedItemIds' ); var fields = select.val(); var fields2 = $( '#SelectedItemIds' ).val();` usually produces arrays of strings for both, but occasionally one or the other comes out as objects. It only did it the first few times, so I'm hoping there was something wrong with the environment and it's fine now. If it happens again I'll update the question. – DCShannon Feb 10 '15 at 04:57
1

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

Butani Vijay
  • 4,181
  • 2
  • 29
  • 61