Search code examples
javascriptjquerywebselectdropdown

How to store multiple Select option on diferent variables using Jquery


I would like to know how can I store different options selected on a select input and put them on different variables.

example:

<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
    <div class="form-group">
        <label for="operacoes">Operações Possíveis</label>
        <div class="input-group">
            <select class="selectpicker show-tick show-menu-arrow" data-width="100%" title="Clique aqui para selecionar um nível .." id="operacoes" name="operacoes[]" multiple>
                <option value="1">Adiciona</option>
                <option value="1">Remove</option>
                <option value="1">Altera</option>
                <option value="1">Pesquisa</option>
            </select>
        </div>
    </div>
</div>

and get the result in different variables :

var a = $('#operacoes').val(1);
var b = $('#operacoes').val(1);
var c = $('#operacoes').val(1);
var d = $('#operacoes').val(1);

and if not selected .val(0);


Solution

  • $('selector').val() will return selected values in array. Without selecting any values below code will print undefined and that is obvious. Hope below answer will help to solve your problem.

    JavaScript:

    function getSelectedValue() {
      const values = $('#operacoes').val();
    
      $('#selectedValues').html(values[0] + ', ' + values[1]);
    }
    

    HTML Code:

    <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
        <div class="form-group">
            <label for="operacoes">Operações Possíveis</label>
            <div class="input-group">
                <select class="selectpicker show-tick show-menu-arrow" data-width="100%" title="Clique aqui para selecionar um nível .." id="operacoes" name="operacoes" multiple>
                    <option value="Adiciona">Adiciona</option>
                    <option value="Remove">Remove</option>
                    <option value="Altera">Altera</option>
                    <option value="Pesquisa">Pesquisa</option>
                </select>
            </div>
        </div>
    </div>
    
    <input type="button" onclick="getSelectedValue()" value="Print Selected Value" />
    <div id="selectedValues"></div>