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 */
});
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.– LeAndrade
HTML is poorly formed. The empty option has to have tag closure.
– Marcelo Shiniti Uchimura