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

Laravel中获取下拉框选中ID并联动显示对应数据库价格

实现下拉选项切换时价格实时更新

方案一:前端直接读取预存数据(无需后端请求)

适合价格不会频繁变动的场景,直接把价格存在下拉选项的自定义属性里,切换时直接读取更新,响应速度快。

先修改视图代码,给价格显示标签加ID,同时给每个<option>添加data-price属性存储对应价格:

<div class="form-group col-md-12" style="display:flex;">
    <label style="margin-right:10px;">Items<span class="text-danger">*</span></label>
    <select style="margin-right:10px;" name="product_id" id="product_id" class="btn btn-primary">
        @foreach ($listitem as $ll)
            <option value="{{ $ll->id }}" data-price="{{ $ll->price }}">
                {{ $ll->name }} -- {{ number_format($ll->price) }}
            </option>
        @endforeach
    </select>

    <label style="margin-right:10px;">Qty<span class="text-danger">*</span></label>
    <input type="number" class="form-control" required name="qty">
</div>

<div class="form-group col-md-12">
    <label>Price : </label>
    <!-- 给价格标签加ID,方便JS定位修改 -->
    <label id="product_price">{{ number_format($listitem->first()->price) }}</label>
</div>

<script>
    // 获取下拉框和价格标签元素
    const productSelect = document.getElementById('product_id');
    const priceLabel = document.getElementById('product_price');

    // 监听下拉框切换事件
    productSelect.addEventListener('change', function() {
        // 获取当前选中选项的原始价格
        const selectedPrice = this.options[this.selectedIndex].dataset.price;
        // 格式化价格并更新显示
        priceLabel.textContent = new Intl.NumberFormat().format(selectedPrice);
    });
</script>

方案二:通过AJAX请求后端获取实时价格

如果价格可能动态变化(比如后台随时修改),需要每次切换都从后端获取最新价格,就用这种方式:

1. 后端添加路由和控制器方法

在routes/web.php中添加路由:

Route::get('/product-price/{id}', [ProductController::class, 'getPrice'])->name('product.price');

在对应的ProductController.php中实现方法:

public function getPrice($id)
{
    $product = \App\Models\Product::findOrFail($id);
    return response()->json(['price' => $product->price]);
}

2. 修改视图并添加AJAX逻辑

<div class="form-group col-md-12" style="display:flex;">
    <label style="margin-right:10px;">Items<span class="text-danger">*</span></label>
    <select style="margin-right:10px;" name="product_id" id="product_id" class="btn btn-primary">
        @foreach ($listitem as $ll)
            <option value="{{ $ll->id }}">
                {{ $ll->name }} -- {{ number_format($ll->price) }}
            </option>
        @endforeach
    </select>

    <label style="margin-right:10px;">Qty<span class="text-danger">*</span></label>
    <input type="number" class="form-control" required name="qty">
</div>

<div class="form-group col-md-12">
    <label>Price : </label>
    <label id="product_price">{{ number_format($listitem->first()->price) }}</label>
</div>

<script>
    const productSelect = document.getElementById('product_id');
    const priceLabel = document.getElementById('product_price');

    productSelect.addEventListener('change', function() {
        const productId = this.value;
        
        // 发送AJAX请求获取最新价格
        fetch(`/product-price/${productId}`)
            .then(response => response.json())
            .then(data => {
                priceLabel.textContent = new Intl.NumberFormat().format(data.price);
            })
            .catch(error => {
                console.error('获取价格失败:', error);
                priceLabel.textContent = '获取失败';
            });
    });
</script>

注意事项

  • 方案一中的data-price要存原始价格数值,不要存格式化后的字符串,方便后续处理。
  • 方案二中要确保路由地址正确,且控制器能正常查询到对应商品。
  • 如果项目已引入jQuery,AJAX部分可以用$.get()简化写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:55:33