Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get the selected text as comma separated from select box

<select id="testID" multiple="multiple">
   <option value="1">test Value1</option>
   <option value="2">test Value2</option>
   <option value="3">test Value3</option>
   <option value="4">test Value4</option>
   <option value="5">test Value5</option>
  <option value="6">test Value6</option>
</select>

<input type="button" value="Get dropdown selected Value" id ="select-values">

i want to get the comma separated selected text.

I tried ,

 $("#select-values").click(function () {
     $("select option:selected").text();
});

lets say i have selected first two select options but i am getting the value test Value1test Value2

i want it to be test Value1,test Value2

like image 777
monda Avatar asked Nov 25 '13 11:11

monda


4 Answers

Try

fiddle demo

$("#select-values").click(function () {
    var option_all = $("select option:selected").map(function () {
        return $(this).text();
    }).get().join(',');
    console.log(option_all);
});
like image 149
Tushar Gupta - curioustushar Avatar answered Oct 20 '22 23:10

Tushar Gupta - curioustushar


This feels like the quickest way:

$('#testID').val().toString()

I'm too lazy to write a for loop for this

like image 42
Andrei C Avatar answered Oct 20 '22 23:10

Andrei C


Try:

var selectedItems = ($.map($("select[id*=select-values] option:selected"), function(item, i) { return $(item).text() })).join(", ");

like image 3
Maya Shah Avatar answered Oct 21 '22 01:10

Maya Shah


Try something like this

$(document).ready(function () {
    $("#select-values").click(function () {
        var val = [];
        $("select option:selected").each(function () {
            val.push(this.text);
        });
        alert(val.join(','));
    });
});
like image 2
rajesh kakawat Avatar answered Oct 21 '22 00:10

rajesh kakawat