Henrique Van Klaveren Henrique Van Klaveren - 2 years ago 103
jQuery Question

Error on populate Select with JSON

I would like some help in my code :

When I try to use a variable instead of the key name of the array, my return is NULL, someone could give me an idea of how to use a variable rather than a fixed name.

Thank you.

var json = '[{"id":"8","top_cadastro_clientes_name":"USS SOLUCOES GERENCIADAS LTDA"},{"id":"9","top_cadastro_clientes_name":"AXA - INTER PARTNER ASSIST"},{"id":"10","top_cadastro_clientes_name":"BRASIL ASSISTENCIA SA"},{"id":"11","top_cadastro_clientes_name":"EUROP ASSISTANCE"},{"id":"12","top_cadastro_clientes_name":"MONDIAL SERVICOS LTDA"},{"id":"13","top_cadastro_clientes_name":"PARTICULAR ATIVO"}]';

var select = $('select');
var referencedcolumn = 'id';
var referencedfield = 'top_cadastro_clientes_name';
var opts = $.parseJSON(json);

$.each( opts, function(key, val) {
select.append('<option value="'+val.id+'">'+val.id+'-'+val.referencedfield+'</option>');

console.log('why print NULL when i use variable for field???'+val.referencedcolumn);

<select class="form-control" name="select" data-referencedtable="" data-referencedcolumn="" data-referencedfield="">
<option value="0" selected="selected">Selecione...</option>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer Source

You're looking for array syntax:

$.each( opts, function(key, val) {
  select.append('<option value="'+val[referencedcolumn]+'">'+val[referencedcolumn]+'-'+val[referencedfield]+'</option>');
  console.log('print id column value: '+val[referencedcolumn]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download