javascripthtmljquery-select2multiple-select

How to receive in JS selections from html using select2


I want to receive in JS the selected values from html. In html I'm using multi-select box with selected2 library. I was able to do it for a normal single choice such as <select class="form-control" id="companies" >.

Could anybody tell me how to do it for a multiple selects with select2?

html

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>

<form>
    <div class="form-group">
        <label>Airline companies</label>
        <p>
            <select class="js-example-basic-multiple" id="companies" name="states[]" multiple="multiple" style="width: 120%">
            <!-- select class="form-control" id="companies" --> // if I don't use multiple select with select2, it worked

               <option selected>Select companies</option>
               <option value="one">First</option>
               <option value="two">Second</option>
               ...
            </select>
        </p>
    </div>
    <button  class="btn btn-primary" type='button' id="button">Refresh</button>
</form>

JS

company = getSelectedOption('companies')

function getSelectedOption(id){
/* function to get the selected value from the dropdowns */
    let select = document.getElementById(id);
    let value = select.options[select.selectedIndex].value;
    return value
}

Solution

  • You can get selected value by using jQuery method .val():

    
    var company = getSelectedOption('companies');
    
    function getSelectedOption(id){
        return $('#' + id).val();
    }