get all the values of a select when loading the page


I have the following code, it turns out that I want to capture all the Values of a Select hidden once the page is loaded in Html , capture them in Javascript and send them by means of a JSON to the controller of 'laravel.

Here is the code, thank you very much for your help:

                <select name="annios[]" id="annios" hidden multiple="multiple">
                    @foreach($precebo as $fecha)
                        <option value="{{$fecha->año_destete}}">{{$fecha->año_destete}}</option>

This is what the array generates:

var array =$("[name='annios[]']").val(); 

I think it may be a mistake when I generate it.

asked by Juan Esteban Yarce 28.03.2018 в 23:45

2 answers


The problem is that .val() is going to return only the selected value of select (or failing that of the first option ) but not an array of values of option . Also, as it is being done, only the select is selected and not the option .

What you could do is select all option , scroll them using each and save their values in an array. Something like this:

var miArray = [];

$("[name='annios[]'] option").each(function() {

<script src=""></script>

  <select name="annios[]" id="annios" hidden multiple="multiple">
    <option value="2015">2015</option>
    <option value="2016">2016</option>
    <option value="2017">2017</option>
    <option value="2018">2018</option>
answered by 29.03.2018 в 01:37

Generalized function, for wider use.

function current__select__values(id) {
 const e = document.getElementById(id);
 return Array.apply(null,Array(e.options.length)).
 map((cur, i, arr) => {
  return arr[i] = {
            selectName: e.options[i].text,
            selectValue: e.options[i].value

var data = current__select__values("f"); // Datos guardados aquí
<select id="f">
<option value="H4"> 4 Hamburgesas </option>
<option value="B9"> 9 Bebidas </option>
answered by 29.03.2018 в 16:00