Display | Scrub a field when selecting data in Select

1

In this code the select appears with the Cities grouped as desired, but I would like to click on any of the select 'store' options to open in a table below the selected store address only.

HTML

<div> <select id="cities"></select> </div>

<div> <select id="loja selecionada"></select> </div>

JAVASCRIPT

var values = [
{ "Estado": "São Paulo",
  "OrderID": "Loja1",
  "Endereco":"Rua 10"},
{"Estado": "São Paulo",
  "OrderID": "Loja2",
  "Endereco":"Rua 10"}, 
{ "Estado": "São Paulo",
  "OrderID": "Loja3",
  "Endereco":"Rua 10"}, 
{ "Estado": "Rio de Janeiro",
  "OrderID": "Loja1",  
  "Endereco":"Rua 10"},
{ "Estado": "São Paulo", 
  "OrderID": "Loja4",
  "Endereco":"Rua 10"}, 
{ "Estado": "Mato Grosso",
  "OrderID": "Loja5",
  "Endereco":"Rua 10"},
{ "Estado": "São Paulo", 
  "OrderID": "Loja6",
  "Endereco":"Rua 10"}, 
{ "Estado": "Minas Gerais",
  "OrderID": "Loja1",
  "Endereco":"Rua 10"},
{ "Estado": "São Paulo",
  "OrderID": "Loja7",
  "Endereco":"Rua 10"},
{ "Estado": "Minas Gerais", 
  "OrderID": "Loja2",
  "Endereco":"Rua 10"}, 
{ "Estado": "São Paulo", 
  "OrderID": "Loja8",
  "Endereco":"Rua 10"}
];

var items = {},
base, key;
$.each(values, function(index, val) {
key = val.Estado;
if (!items[key]) {
   items[key] = [];
}
items[key].push(val.OrderID);
});

var $select = $('#cities');
$.each(items, function(index, val) {

var optgroup = $('<optgroup>');
    optgroup.attr('label', index);

$.each(val, function(index, val) {
    optgroup.append($('<option>', {
    text: val
    }));
});

$select.append(optgroup);
});
    
asked by anonymous 14.03.2016 / 15:51

1 answer

1

Change the assembly of the options to save the index:

$.each(val, function(index, val) {
  optgroup.append($('<option>', {
    text: val,
    value: index //index
  }));
});

Then just implement the change in the select to get the address and display in the field:

$('#cities').change(function() {
  var endereco = values[$(this).val()].Endereco;
  $('#endereco').text(endereco);
});

HTML:

<label>Endereço: <span id="endereco"></span></label>

Follow jsfiddle :)

    
14.03.2016 / 16:25