Checking multiple select of same "name", if empty with Jquery

0

I have tried in several ways but I have not succeeded in creating a window.alert (); com return false; if no select field of name="product_qtd []" is selected or if it does not exist, but to no avail, I have checked in here and no response has adapted to what I need.

Example:

<select name="produto_qtd[]" class="form-control">
<option value="">Produto X - Selecione quantidade</option>
<option value="10">10 itens</option>
<option value="20">20 itens</option>
<option value="50">50 itens</option>
</select>


<select name="produto_qtd[]" class="form-control">
<option value="">Produto Y - Selecione quantidade</option>
<option value="10">10 itens</option>
<option value="20">20 itens</option>
<option value="50">50 itens</option>
</select>

Or if the select does not exist, also check and return a window.alert (); and return false; reporting "No quantity selected," only.

There are cases where the select related to the product disappears due to the declared value of the product being higher than the contract plan, and other cases the select exists but no value with value was selected.

    
asked by anonymous 22.05.2018 / 18:05

2 answers

0

Make a filter on the select that has some value.

if ($("select[name='produto_qtd[]']").toArray().filter(function (e) { return $(e).val(); }).length > 0)
    alert('algum selecionado');
else
    alert('nenhum selecionado');
    
22.05.2018 / 19:06
0

You can use a map to bring up the selected values.

$(document).ready(function() {
  var selecionados;
  $('[name="produto_qtd[]"]').on('change', function() {
     selecionados = $('[name="produto_qtd[]"] :selected')
                       .map(function(){
                            if($(this).val() != '')
                            return $(this).text();
                        }).get();
    console.log(selecionados);
  });
  
  $("#validar").on('click', function(){
      if(selecionados == null)
        alert("Nenhum produto selecionado");
      else{
        alert("Os seguintes produtos foram selecionados: \r\n" + selecionados.toString());
      }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="produto_qtd[]" class="form-control">
  <option value="">Produto X - Selecione quantidade</option>
  <option value="10">10 itens</option>
  <option value="20">20 itens</option>
  <option value="50">50 itens</option>
</select>


<select name="produto_qtd[]" class="form-control">
  <option value="">Produto Y - Selecione quantidade</option>
  <option value="10">10 itens</option>
  <option value="20">20 itens</option>
  <option value="50">50 itens</option>
</select>
<button id="validar">Verificar</button>
    
22.05.2018 / 19:13