You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Datatables每行select2多选下拉框的全部选中值存入Livewire的wire:model

问题根因

  1. 你没有给select标签加multiple属性,select2默认只能单选,自然只能返回单个值
  2. 你当前wire:model绑定的是单个变量$fruit,而非你声明的数组$fruits,每次赋值都会直接覆盖原有值
  3. jQuery事件绑定逻辑冗余,且直接覆盖赋值没有做选中值的合并处理

修复步骤

1. 修改Blade视图代码

给select标签加multiple属性,同时调整wire:model绑定规则,如果你需要保存所有行的所有选中值,建议绑定为数组格式fruits.{{$loop->index}},这样每一行的选中值会自动按行索引存到全局$fruits数组里:

@foreach($majorfruits as $data)
     <tr>
        <td>
             <!-- 加multiple属性,绑定数组格式的wire:model -->
             <x-forms.select wire:model="fruits.{{$loop->index}}" id="fruit-id-{{$loop->iteration}}" multiple>
                     <x-slot name="option">
                            @foreach ($fruitsOption as $item) 
                            {{-- 注意这里别和绑定的$fruits重名,你原来的选项遍历变量名和绑定数组重名了会冲突,需提前在控制器把选项列表变量改为$fruitsOption --}}
                                        <option value="{{$item->id}}">{{$item->name}}</option>
                            @endforeach
                        </x-slot>
             </x-forms.select>
         </td>
     </tr>
@endforeach

2. 确认Livewire组件属性声明

组件中保持数组类型声明即可:

public array $fruits = [];

3. 优化select2的jQuery绑定代码

不用循环100次绑定事件,直接用属性选择器匹配所有行的select元素,多选模式下select2("val")默认返回选中值的数组,直接赋值给对应的数组索引即可:

// 匹配所有id以fruit-id-开头的select元素,统一初始化绑定事件
$('[id^="fruit-id-"]').select2().on('change', function (e) {
    // 提取当前select的行索引,你的id规则是fruit-id-{{$loop->iteration}},iteration从1开始所以减1匹配数组0起始索引
    const rowIndex = this.id.split('-').pop() - 1;
    const selectedValues = $(this).select2("val");
    // 赋值给对应行的数组元素
    @this.set(`fruits.${rowIndex}`, selectedValues);
});

如果你不需要按行区分选中值,只需要把所有选中的id去重后放到一个一维数组里,可以把赋值逻辑改成合并去重:

$('[id^="fruit-id-"]').select2().on('change', function (e) {
    // 遍历收集所有行的选中值
    let allSelected = [];
    $('[id^="fruit-id-"]').each(function() {
        const vals = $(this).select2("val");
        if(vals) allSelected = allSelected.concat(vals);
    });
    // 去重后赋值给全局$fruits数组
    @this.set('fruits', [...new Set(allSelected)]);
});

内容的提问来源于stack exchange,提问作者quezera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:48:02