Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all selected option text form multi select Using Javascript

I have problem in get all selected option in multi select

<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>

Bellow is my code and its return me only first selected option

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>";
        }

So please suggest me how can i get all selected option text and where I make mistake ?

like image 378
user123 Avatar asked Feb 20 '13 05:02

user123


People also ask

How do you select multiple options in JavaScript?

To select multiple options in a drop-down list, use the multiple properties. It allows you to select more than one option while pressing CTRL key.

How do I get the text value of a selected option in JavaScript?

function myNewFunction(element) { var text = element. options[element. selectedIndex]. text; // ... }


3 Answers

Your comment please suggest me how can i get all selected option text, So 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);    } }); 
like image 169
Jai Avatar answered Sep 18 '22 14:09

Jai


do all in one line now

var text = $('#selector option:selected').toArray().map(item => item.text).join();

it return like this:

text1,text2,text3,text4
like image 41
peiman F. Avatar answered Sep 19 '22 14:09

peiman F.


// 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;
}

pass this function your select box as like..

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

it will return the array of selected values

By using Jquery

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

the val function called from the select will return an array if its a multiple.

like image 43
Talha Avatar answered Sep 17 '22 14:09

Talha