Skip to content Skip to sidebar Skip to footer

How To Get The Selected Text Of Options In Multiple Select?

I am trying to get the selected option in multiple select, I can get the value in the form of an array, but I can't get the text of the option. On $(e.target).text(), I am getting

Solution 1:

Using .text() on a select will give the text of the control - i.e. all of the options, not just the selected ones.

To get the selected text (not value as you pointed out you can already get), you can use:

$(this).find("option:checked").map((i,e)=>$(e).text()).toArray();

Here, $(this).find("option:checked") will give you the option elements that have been selected while the .map will return the .text() for each of those values into a jquery array, with .toArray() to convert to a normal js array.

$(function() {
  $('#sizeAddCategory').change(function() {
    var selected = $(this).find("option:checked").map((i,e)=>$(e).text()).toArray();
    console.log("selected", selected);
    $('#textAreaAddCategory').val(selected.join(','));
  });
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="form-group col-sm-6"><labelfor="sel1">Select Sizes (hold ctrl or shift (or drag with the mouse) to select more than one):</label><br/><selectrequiredclass="form-control"id="sizeAddCategory"multiple><optionvalue="1">one</option><optionvalue="2">two</option><optionvalue="3">three</option><optionvalue="4">four</option></select></div><divclass="form-group col-md-3"><labelfor="name">Selected Sizes</label><br/><textarearequireddisabledrows="4"class="form-control"id="textAreaAddCategory"></textarea></div>

Solution 2:

It's because the target that you're defining is in the select tag. Instead of using:

$('#sizeAddCategory').change(function(e) {

use:

$('.option-category').click(function(e) {

and add a class in the options:

<option value="{{$size->id}}" class="option-category">{{$size->name}}</option>

Solution 3:

you write :

var selected = $(e.target).text();

you should get the value of selectbox and you should write

var selected = $(e.target).val();

Solution 4:

oh my god i right now understand what did you mean ok

write :

$("#selectBox").change(function(e){

    var x = $(e.target).find("option:checked").text();

    console.log(x);
});

Post a Comment for "How To Get The Selected Text Of Options In Multiple Select?"