2017-07-04 25 views
0

我有一個json字符串,我希望將其添加到select2多選搜索輸入中。我得到的地圖如下錯誤在多選的Select2搜索表單上設置值

無法讀取的不確定

從控制檯日誌中的JSON字段屬性 '地圖' 是

[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}] 

而且JS代碼

var employees = $(this).attr('data-employees'); 
    console.log(employees); 

    $("select[name='employees[]']").val(employees.data.map(function(x) { 
    return x.id; })); // Set the selected data before show it. 
      $('select').select2() 

HTML

<select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select> 
+1

如果'employees'的cosole.log爲您提供了您提問中提供的對象數組,那麼只需簡單地移除數據並像這樣執行即可:'.val(employees.map(function(x){...' –

+0

當數據是刪除,我得到「employees.map不是一個函數」 –

回答

1

,我可以看到你是從元素的屬性得到這個數組,如果你是,大概的console.log是一個字符串的話,試試這個:

var employees = JSON.parse($(this).attr('data-employees')); 
console.log(employees); 

$('select').select2(); // init with select2 
$("select[name='employees[]']").val(employees.map(function(x) { 
    return x.id; // Set the selected data before show it. 
})) 
.trigger("change"); 

如果你看到這個

var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]'); 
 
console.log('The whole array:', employees); // you have a valid array 
 

 
var ids = employees.map(function(x){ return x.id; }) 
 
console.log('Employee ids only: ', ids);

編輯

+0

不再像這樣得到一個錯誤。 console.log返回[Object,Object]。模態選擇字段爲空而沒有值。 –

+0

我編輯了我的答案。如果你在console.log中也看到了這個,你的問題就在別的地方;]。 –

+0

是的。我看到了你的結果。我的問題是在其他地方將數據放在選擇框中。我猜測一些東西是不完整的:$('select')。select2() –