Taking information from a select and passing an array

Asked

Viewed 554 times

1

I want to take all the fields of one select and store them in a array. I thought I’d do it this way, but it didn’t work.

var lista = [];
lista = $('#Model').text();

$('#Model').append('<option value="' + data.ModelID + '">' + data.Name + '</option>');

2 answers

1

1) In the click one-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>

<select id="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 the 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>
<select id="select1">
  <option value="1">Opt 1</option>
  <option value="2">Opt 2</option>
  <option value="3">Opt 3</option>
</select>

  • Thanks Vigilio, but then in this case I have ID and I have the text, as I do to take both and store?

  • @Fabiosouza put your Select in the question please

  • select is fed a json bringing the bank results

  • @Fabiosouza did the editing!

0

You need to loop the items in the 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

Browser other questions tagged

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