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

Laravel实现产品选择后自动填充表单字段方案咨询

实现产品选择后自动填充表单字段的思路

1. Produits数据表迁移代码

public function up()
{
    Schema::create('produits', function (Blueprint $table) {
        $table->id();
        $table->string('reference')->nullable();
        $table->string('libelle')->nullable();
        $table->string('entrepot_id')->nullable();
        $table->string('tva')->nullable();
        $table->string('etat_vente')->nullable();
        $table->string('etat_achat')->nullable();
        $table->string('description')->nullable();
        $table->string('limit_stock_alerte')->nullable();
        $table->string('stock_optimal')->nullable();
        $table->string('prix_vente')->nullable();
        $table->string('prix_vente_min')->nullable();
        $table->string('prix_revient')->nullable();
        $table->string('poids')->nullable();
        $table->string('user_created_id')->nullable();
        $table->string('user_updated_id')->nullable();
        $table->timestamps();
    });
}

2. 获取产品列表的控制器代码

public function show($id)
{
    $propositions = PropoCom::where('id','=',$id)->first();
    $produits = Produit::where('etat_vente', 1)->get();
    return view('layouts.commerce.details-propo-brouillon', compact('propositions', 'produits'));
}

3. 当前表单代码

<form action="">
    <tr>
   @foreach ($produits as $produit)
   <th scope="row">
   <label for="inputEmail4">Produits prédéfinis en vente</label>
   <select id="inputState" class="form-control w-75 mb-3">
   <option>...</option>
   <option>{{$produit->reference}} - {{$produit->libelle}} - 
   @if ($produit->stocks->isNotEmpty())
   {{ $produit->stocks->sortByDesc('created_at')->first()->nbr_piece }}
   @else
   @endif - {{ number_format($produit->prix_vente, 0, ',', ' ') }} FCFA
   </option>
   @endforeach
   </select>
   </th>
   <td>
   <label for="inputEmail4">TVA</label>
   <select id="inputState" class="form-control w-100 mt-2">
   <option>...</option>
   <option>0%</option>
   <option selected>18%</option>
   </select>
   </td>
   <td>
   <label for="inputEmail4">PRIX DE VENTE</label>
   <input type="text" class="form-control w-75 mt-2">
   </td>
   <td>
   <label for="inputEmail4">QUANTITE</label>
   <input type="text" class="form-control w-75 mt-2">
   </td>
   <td>
  <label for="inputEmail4">REDUCTION</label>
  <input type="text" class="form-control w-75 mt-2">
  </td>
  <td>
  <label for="inputEmail4">PRIX DE REVIENT</label>
  <input type="text" class="form-control w-75 mt-2">
  </td>
  <td>
  <button type="button" class="btn btn-secondary mt-4">AJOUTER</button>
  </td>
  </tr>
</form>

4. 需求说明

当用户从产品下拉菜单选择一款产品时,自动填充TVA选择框、售价输入框、成本价输入框的内容,使用所选产品的对应信息。

产品下拉菜单代码:

@foreach ($produits as $produit)
   <th scope="row">
   <label for="inputEmail4">Produits prédéfinis en vente</label>
   <select id="inputState" class="form-control w-75 mb-3">
   <option>...</option>
   <option>{{$produit->reference}} - {{$produit->libelle}} - 
   @if ($produit->stocks->isNotEmpty())
   {{ $produit->stocks->sortByDesc('created_at')->first()->nbr_piece }}
   @else
   @endif - {{ number_format($produit->prix_vente, 0, ',', ' ') }} FCFA
   </option>
   @endforeach

需要自动填充的字段:

  • TVA选择框:
<label for="inputEmail4">TVA</label>
<select id="inputState" class="form-control w-100 mt-2">
<option>...</option>
<option>0%</option>
<option selected>18%</option>
</select>
  • 售价输入框:
<label for="inputEmail4">PRIX DE VENTE</label>
<input type="text" class="form-control w-75 mt-2">
  • 成本价输入框:
<label for="inputEmail4">PRIX DE REVIENT</label>
<input type="text" class="form-control w-75 mt-2">

实现思路

步骤1:修正下拉菜单循环逻辑

当前下拉菜单的循环写法错误,会生成多个<select>元素,正确写法应该是在单个<select>内部循环生成选项,同时给每个选项存储需要填充的产品数据:

<th scope="row">
    <label for="product-select">Produits prédéfinis en vente</label>
    <select id="product-select" class="form-control w-75 mb-3">
        <option value="">...</option>
        @foreach ($produits as $produit)
            <option 
                value="{{ $produit->id }}" 
                data-tva="{{ $produit->tva }}" 
                data-prix-vente="{{ $produit->prix_vente }}" 
                data-prix-revient="{{ $produit->prix_revient }}"
            >
                {{ $produit->reference }} - {{ $produit->libelle }} - 
                @if ($produit->stocks->isNotEmpty())
                    {{ $produit->stocks->sortByDesc('created_at')->first()->nbr_piece }}
                @endif - 
                {{ number_format($produit->prix_vente, 0, ',', ' ') }} FCFA
            </option>
        @endforeach
    </select>
</th>

步骤2:给目标字段添加唯一标识

为了准确操作需要填充的字段,给它们设置唯一ID:

<!-- TVA选择框 -->
<select id="tva-select" class="form-control w-100 mt-2">
    <option value="">...</option>
    <option value="0%">0%</option>
    <option value="18%">18%</option>
</select>

<!-- 售价输入框 -->
<input type="text" id="prix-vente-input" class="form-control w-75 mt-2">

<!-- 成本价输入框 -->
<input type="text" id="prix-revient-input" class="form-control w-75 mt-2">

步骤3:编写JS实现自动填充

在页面底部添加JavaScript代码,监听下拉框的选择事件,提取选中选项的产品数据并填充对应字段:

document.getElementById('product-select').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    // 获取产品属性
    const tva = selectedOption.dataset.tva;
    const prixVente = selectedOption.dataset.prixVente;
    const prixRevient = selectedOption.dataset.prixRevient;
    
    // 填充TVA选择框
    document.getElementById('tva-select').value = tva ? `${tva}%` : '';
    // 若数据表中tva已带%,直接赋值:document.getElementById('tva-select').value = tva || '';
    
    // 填充售价
    document.getElementById('prix-vente-input').value = prixVente ? numberFormat(prixVente, 0, ',', ' ') : '';
    
    // 填充成本价
    document.getElementById('prix-revient-input').value = prixRevient ? numberFormat(prixRevient, 0, ',', ' ') : '';
});

// 模拟PHP的number_format格式化函数
function numberFormat(num, decimals, decPoint, thousandsSep) {
    num = num.toString().replace(/[^0-9+\-Ee.]/g, '');
    const n = !isFinite(+num) ? 0 : +num;
    const prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
    const sep = thousandsSep || ',';
    const dec = decPoint || '.';
    
    let s = (prec ? n.toFixed(prec) : Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = (s[1] || '') + new Array(prec - (s[1] || '').length + 1).join('0');
    }
    return s.join(dec);
}

补充说明

  • 注意数据表中tva字段的存储格式:若存储的是数字(如"18")则需拼接%,若已带%则直接赋值
  • 确保所有元素ID唯一,避免DOM选择冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:17:03