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

Laravel中通过JavaScript匹配数组设置下拉框选中状态

实现预加载数据下的产品生产地点下拉框匹配功能

需求概述

  • 控制器向edit.blade.php视图传递生产地点数组与产品数组
  • 视图渲染生产地点下拉选择框,同时展示产品列表
  • 点击任意产品时,利用预加载的产品数据,将对应生产地点的下拉选项设为选中状态,全程无需后端请求

完整实现代码

Blade视图部分(下拉框与产品列表基础结构)

<select class="form-control m-bot15" id="ProduktionsortSelect"  
  name="Produktionsort" data-placeholder="dadada">
  <option value="">----</option>
  @foreach ( $data['produktionsort'] as $produkteOrt )
    <option value="{{ $produkteOrt->Ort }}" id="{{ $produkteOrt->Ort }}">     
      {{ $produkteOrt->Ort }}
    </option>
  @endforeach  
</select>

<!-- 产品列表示例:需确保每个产品项的单选按钮带class="flexRadioDefault",id为产品对应索引 -->
<div class="product-list">
  @foreach($data['produktarray'] as $index => $product)
    <div class="product-item">
      <input type="radio" class="flexRadioDefault" id="{{ $index }}" name="selected-product">
      <span>{{ $product['prodDatName'] }}</span>
    </div>
  @endforeach
</div>

<input type="hidden" id="produktId" />

JavaScript逻辑部分

// 提前注入产品数组,避免点击时重复解析
const productArray = @json($data['produktarray'] ?? []);
const elementArr = document.getElementsByClassName("flexRadioDefault");

// 为每个产品选项绑定点击事件
for (let i = 0; i < elementArr.length; i++) {
  const element = elementArr[i];
  element.addEventListener('click', function() {
    // 切换选中项背景样式
    element.parentElement.parentElement.style.backgroundColor = 'lightgrey';
    for (let j = 0; j < elementArr.length; j++) {
      const e = elementArr[j];
      if (element !== e) {
        e.parentElement.parentElement.style.backgroundColor = '#ebeef0';
      }
    }

    // 获取当前选中产品索引并填充数据
    const currentElementID = parseInt(element.id);
    fillInProdukt(productArray[currentElementID]);
  });
}

function fillInProdukt(produkt) {
  // 设置产品ID
  document.getElementById("produktId").value = produkt['id'];

  // 匹配并选中对应生产地点:直接通过value匹配,比遍历更高效
  const productionSelect = document.getElementById("ProduktionsortSelect");
  productionSelect.value = produkt['prodDatProduktionsOrt'] || '';
  
  // 如需填充其他产品字段,可在此扩展
  // document.getElementById('Menge').value = produkt['prodDatMenge'];
  // document.getElementById('anzahlPfosten').value = produkt['prodDatAnzahlPfosten'];
}

优化点说明

  1. 性能优化:将产品数组的JSON转换放在全局作用域,避免每次点击事件触发时重复执行PHP代码注入
  2. 简化选中逻辑:利用下拉框的value属性直接匹配生产地点值,无需遍历所有选项,代码更简洁高效
  3. 可读性提升:变量名改为更语义化的命名,降低后续维护成本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 09:45:28