Collect value of multiple select with jquery


I have a multiple select from which I need to check the value with jquery. I need to know how to pick up the value of that select, because if it's empty it returns this:

But putting it in a if ([] === $("#comercial_lista_calc").val()) returns false and if I put !== it does not work correctly either because it does not enter the if.

<label for="comercial_lista_calc">{{ "Comercial"|trans }}</label><br>
        <select id="comercial_lista_calc" name="comercial_lista_calc[]" class="chosen selectMed" multiple="true">
            <option value="todos">{{ "Todos.comerciales"|trans }}</option>
            {% for comercial in comerciales %}
                <option value="{{ }}">{{ comercial.username|title }}</option>
            {% endfor %}

The solution has been this: if(0 < $("#comercial_lista_calc").val().length)

asked by Pavlo B. 21.05.2018 в 16:14

2 answers


You could put it in an change event and evaluate it there.

$("#comercial_lista_calc").on('change', function() {
  var val = $(this).val();
  // te muestra un array de todos los seleccionados
answered by 21.05.2018 в 16:28

The problem is in this comparison:

if ([] === $("#comercial_lista_calc").val())

What it does is evaluate if two objects are equal ...

If you want to evaluate if the value is empty, you can do it by means of a simple if(!valorDelSelect){ or by means of a ternary operator that allows you to assign a unique variable depending on whether it is empty or not and use that variable.

For example:

$('#comercial_lista_calc').on('change', function() {
  var selValue = this.value;
  var selStatus = (selValue) ? "Tiene el valor: " + selValue : "Está vacío";
<script src=""></script>
<label for="comercial_lista_calc">Lista</label><br>
<select id="comercial_lista_calc" name="comercial_lista_calc[]" class="chosen selectMed" multiple="true">
  <option value="todos">Todos</option>
  <option value="uno">Uno</option>
  <option value="dos">Dos</option>
  <option value="">Vacío</option>

answered by 21.05.2018 в 16:38