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

如何用JavaScript修改Laravel变量$selectedCategoryId实现分类联动?

动态更新分类下拉框解决方案

先看你现有的Laravel Blade代码:

<div class="form-group">
    <label for="parent_category">Category:</label>
    <select id="parent_category" name="parent_category" class="form-control" required>
        @foreach ($categories as $category)
            @if ($category->parent_id == null)
                <option value="{{ $category->id }}" {{ $selectedCategoryId = $category->id }}>
                    {{ $category->name }}
                </option>
            @endif
        @endforeach
    </select>
</div>

<div class="form-group">
    <label for="category_id">Sub-Category:</label>
        <select id="category_id" name="category_id" class="form-control" required>
            @foreach ($categories as $category)
                @if ($category->parent_id == $selectedCategoryId)
                    <option value="{{ $category->id }}">
                        {{ $category->name }}
                    </option>
                @endif
            @endforeach
        </select>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var parent_category = document.getElementById('parent_category');

        parent_category.addEventListener('change', function() {
            console.log("changed")
        })
    });
</script>

核心问题说明

后端的$selectedCategoryId是服务端渲染时生成的静态变量,JavaScript没法直接修改这个PHP变量。要实现动态更新子分类,得把所有分类数据传到前端,用JS实时过滤生成子分类选项。

修改后的完整代码

<div class="form-group">
    <label for="parent_category">父分类:</label>
    <select id="parent_category" name="parent_category" class="form-control" required>
        @foreach ($categories as $category)
            @if ($category->parent_id === null)
                <option value="{{ $category->id }}" {{ $loop->first ? 'selected' : '' }}>
                    {{ $category->name }}
                </option>
            @endif
        @endforeach
    </select>
</div>

<div class="form-group">
    <label for="category_id">子分类:</label>
    <select id="category_id" name="category_id" class="form-control" required>
        <!-- 初始子分类由JS渲染 -->
    </select>
</div>

<script>
    // 将后端分类数据转为JSON传到前端
    const allCategories = @json($categories);
    const parentSelect = document.getElementById('parent_category');
    const subSelect = document.getElementById('category_id');

    // 渲染子分类下拉框的通用函数
    function renderSubCategories(parentId) {
        // 清空现有选项
        subSelect.innerHTML = '';
        // 过滤出当前父分类对应的子分类
        const subCategories = allCategories.filter(category => category.parent_id == parentId);
        // 生成并添加子分类选项
        subCategories.forEach(category => {
            const option = document.createElement('option');
            option.value = category.id;
            option.textContent = category.name;
            subSelect.appendChild(option);
        });
    }

    // 页面加载完成后初始化子分类,同时监听父分类变化
    document.addEventListener('DOMContentLoaded', function() {
        // 渲染默认选中父分类的子分类
        renderSubCategories(parentSelect.value);

        // 父分类切换时重新渲染子分类
        parentSelect.addEventListener('change', function() {
            renderSubCategories(this.value);
        });
    });
</script>

代码逻辑说明

  1. 数据传递:用@json($categories)把后端的分类集合转成前端JS可直接读取的JSON格式,避免AJAX请求的复杂操作。
  2. 初始化渲染:页面加载完成后,根据父分类默认选中的值,自动渲染对应的子分类。
  3. 动态更新:监听父分类下拉框的change事件,每次选中新父分类时,调用过滤函数重新生成子分类选项。
  4. 修正原有问题:去掉原代码中循环内赋值$selectedCategoryId的写法,改用$loop->first设置默认选中的父分类,避免服务端逻辑混乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 23:58:21