skip to Main Content

I have multiple select that contains options of languages and I want to get the values selected.
I tried that using by retrieve the value from the id but nothing shown in the console.

 $('#language').select2();

<select  id="language" class="form-control" multiple="multiple" data-toggle="select2"> 
     <option value="1">FR</option>
     <option value="1">Eng</option>
     <option value="1">Es</option>
       
</select>


var selectedValues = $('#language').val();
console.log(selectedValues);

2

Answers


  1. You can try this..

    var selectedValues = $('#language').find(':selected').val();
    console.log(selectedValues);
    
    Login or Signup to reply.
  2. selectedValues = $('#language').val();
    

    will give you the array of values of selected options.

    Here is a demo:

    $('#language').select2().on('change', function(e) {
      var selectedValues = $('#language').val();
      console.log(selectedValues);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    <select id="language" class="form-control" multiple="multiple" data-toggle="select2">
      <option value="1">FR</option>
      <option value="2">Eng</option>
      <option value="3">Es</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search