gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:56:39 25 4
gpt4 key购买 nike

我有一个 json 字符串,希望将其添加到 select2 多选搜索输入中。我收到如下 map 错误

Cannot read property 'map' of undefined

控制台日志中的 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>

最佳答案

正如我所看到的,您正在从元素属性获取此数组,如果是的话,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);

已编辑

关于javascript - 在 Select2 搜索表单上设置多选值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com