在Select2搜索表单上设置多选的值

时间:2017-07-04 19:54:53

标签: javascript jquery json

我有一个json字符串,我想添加到select2多选搜索输入。我收到地图错误如下

  

无法读取未定义的属性“map”

控制台日志中的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 个答案:

答案 0 :(得分:1)

我可以看到你从element属性获取这个数组,如果你是,可能是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");

如果你看到这个

&#13;
&#13;
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);
&#13;
&#13;
&#13;

被修改