2016-07-19 7 views
1

でJSONでSELECTを読み込みます固定名ではなく変数を使用する方法について説明します。は、私は私のコードでいくつかの助けをしたいと思いjQueryの

ありがとうございます。

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> 
 
</select> 
 

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

答えて

1

あなたは配列構文を探している:

完全に働いた
$.each(opts, function(key, val) { 
    select.append('<option value="'+val[referencedcolumn]+'">'+val[referencedcolumn]+'-'+val[referencedfield]+'</option>'); 
    console.log('print id column value: '+val[referencedcolumn]); 
}); 
+0

。私はそれが括弧を使うべきであることを知らなかった、それが愚かなものであることを知っていた。 ありがとうございました! –

関連する問題