Take the values of all select options with jQuery

Asked

Viewed 1,495 times

0

I have this <select> which is generated dynamically

<select id="select_exemplo">
    <option id="exemplo">
    <option id="exemplo" value="10">teste 1 </option>
    <option id="exemplo" value="11">teste 2 </option>
    <option id="exemplo" value="18">teste 3</option>
    <option id="exemplo" value="25">teste 4</option>
</select>

I need to take with jQuery in the form of an array all the values contained in value, for example [10,11,18,25]. Code jQuery:

valor= jQuery('#select_exemplo').val()

Just give me back the first one, in case the [10].

  • 2

    The way you did you’re getting the val() of select and not of options and another wrong thing you’re doing is to repeat id s.

  • HTML is poorly formed. The empty option has to have tag closure.

2 answers

6


First thing I did was remove the "example" id, since an html page cannot repeat an id.

You can do it this way

var valores = [];
$('#select_exemplo').find('option').each(function() {
  var valor = $(this).val();
  if(valor != "")
    valores.push(valor);
});
console.log(valores);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select_exemplo">
   <option>
   <option value="10">teste 1 </option>
   <option value="11">teste 2 </option>
   <option value="18">teste 3</option>
   <option value="25">teste 4</option>
</select>

I selected the "select" and used the "find" to get all the "option" and finally made a foreach taking each val and playing at a array.

And finally I made an if not to take empty values.

  • thus returned:[ 0:teste1 teste2 teste3 teste4 1:10 2:11 3:18 4:25 ;]

  • It may be that at the time you went to select the element you used your class in place of your id, and there are two elements with the same class, this way it will take two elements, but one would have this without "value" and the other with, you can see that in the example it takes only the values.

  • I understood, it would be possible for me to also take the 0 position of the array?

  • 1

    If you do not want to take the first "option" for this empty, the code I made will no longer take, since I did "if(value != "" )...", but if you want to remove the first item from the array anyway just do values.splice(0, 1);

1

I gave an overview on his HTML, which was poorly formed: I was not closing the first <option/>, which is empty in your case. If it were not, it would be enough to delegate an attribute value empty, as I exemplified below.

Another thing is that the .val() of <select/> only has the value of <option> selected. To get all <option>s, you need to determine this in your jQuery selector: $("#select_exemplo option") and write an algorithm that lasts for each <option/> and collect the desired information.

$(function () {
  var vals = [], val;
  $("#select_exemplo option").each(function () {
    (val = $(this).val()) && vals.push(val);
  });
  console.log('resposta: ' + vals.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="select_exemplo">
  <option value=''>[Selecione]</option>
  <option value='10'>Maçã</option>
  <option value='11'>Banana</option>
  <option value='18'>Tomate</option>
  <option value='25'>Pêssego</option>
  <option value='52'>Melancia</option>
</select>

The .each() shown above iterates over the selected elements with the jQuery selector, as explained in the API documentation,

Description: Iterate over a jQuery Object, executing a Function for each Matched element.

The reserved word this refers to the iterated jQuery object, when used within the function of callback,

More importantly, the callback is Fired in the context of the Current DOM element, so the keyword this refers to the element.

So, in doing so $(this).val() within the function block passed to $("#select_exemplo option").each() as callback, we are getting the .val() of each <option> contained in the element (<select>) whose id is select_exemplo,

$(function () { // Execute quando acabar de carregar toda a página.

  var vals = [], val; // Declaração das variáveis vals e val

  $("#select_exemplo option")/* < selecione os <option>s filhos 
                                  do item com id select_exemplo*/
                             .each(/* < itere */
                                   function () {
    (val = $(this)/* < pegue o <option> da iteração atual*/
                  .val() /* < pegue o value dele */
                        ) && /* < só continue executando à direita
                                  se não for string vazia */
                             vals.push(val) /* < enfileire val em vals */;
  });
  console.log('resposta: ' + vals.toString());/* < printe a resposta
                                                   separada por ","s */
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.