Getting information from a select and passing in an array

1

I want to get all fields of a select and store them in array . I thought about doing it, but it did not work.

var lista = [];
lista = $('#Model').text();
$('#Model').append('<option value="' + data.ModelID + '">' + data.Name + '</option>');
    
asked by anonymous 21.12.2016 / 22:57

2 answers

1

1) No click of a button :

var items = [];
$(function(){
  $('#btn1').on('click', function(){
    $('#select1 option').each(function(i,v)
    {
      items.push( {value: $(v).val(), text: $(v).text() } );
    });
    console.log(items);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select1">
  <option value="1">Opt 1</option>
  <option value="2">Opt 2</option>
  <option value="3">Opt 3</option>
</select>

<button type="button" id="btn1">Transferir</button>

2) When loading page :

var items = [];
$(function()
{  
    $('#select1 option').each(function(i,v)
    {
      items.push( {value: $(v).val(), text: $(v).text() } );
    });
    console.log(items);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="select1">
  <option value="1">Opt 1</option>
  <option value="2">Opt 2</option>
  <option value="3">Opt 3</option>
</select>
    
21.12.2016 / 23:07
0

You need to loop through the items of select#Model , and store the data of each <option> in the array.

var dados = [];

$('#Model select').each(function (i, select) {
    dados.push({
        Name: select.innerHTML,
        ModelID: select.value
    });
});

// dados[0].Name
// dados[1].Name
    
22.12.2016 / 01:54