yuto__ 2024-06-14 08:37 采纳率: 19.2%
浏览 10

如何在bootstrap中如果有两个select标签做联动,freason选择选项后,选项数据作为参数传入服务器,reason作根据freason传入的参数从数据库获取选项?

在bootstrap中如果有两个select标签做联动,freason选择选项后,选项数据作为参数传入服务器,reason作根据freason传入的参数从数据库获取选项。如何实现这个联动。且如果有多条数据需要填写,则有多个freason和reason需要填写,那么如何让一行freason做出改变时,同一行reason做出联动,而其他bootstrapTable中的reason下拉框不做联动。

  • 写回答

3条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-06-14 08:37
    关注

    引自免费微信小程序:皆我百晓生

    要实现在Bootstrap中两个<select>标签的联动效果,并且当freason选择项改变时,只触发同一行的reason下拉框更新,可以采用以下步骤:

    1. HTML结构设置:首先确保你的HTML结构允许对每个<select>进行独立操作。这里我们使用Bootstrap Table,它是一个基于Bootstrap的表格插件,可以方便地处理表格中的数据。每个<tr>元素将包含两个<select>元素,分别用于freasonreason

    2. JavaScript事件监听:为freason添加事件监听器,当其值改变时,发送请求到服务器获取新的reason选项。这可以通过Ajax调用来实现。

    3. 数据处理与更新:从服务器返回的数据应被解析并用于更新相应的reason下拉框。

    示例代码

    HTML

    <!-- 引入必要的库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.19.1/bootstrap-table.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    
    <table data-toggle="table" id="myTable">
        <thead>
            <tr>
                <th data-field="freason">FReason</th>
                <th data-field="reason">Reason</th>
            </tr>
        </thead>
        <tbody>
            <!-- 动态生成的行 -->
        </tbody>
    </table>
    

    JavaScript

    $(document).ready(function () {
        // 初始化表格
        $('#myTable').bootstrapTable();
    
        // 为所有freason select添加事件监听
        $('#myTable').on('change', 'select[name="freason"]', function (e) {
            var row = $(this).closest('tr');
            var freasonValue = $(this).val();
            
            // 发送Ajax请求获取reason选项
            $.ajax({
                url: '/get_reasons',
                type: 'GET',
                data: { 'freason': freasonValue },
                success: function (data) {
                    // 更新同一行的reason下拉框
                    var reasonSelect = row.find('select[name="reason"]');
                    reasonSelect.empty(); // 清空旧选项
                    
                    // 添加新选项
                    $.each(data, function (index, value) {
                        reasonSelect.append('<option value="' + index + '">' + value + '</option>');
                    });
                }
            });
        });
    });
    

    说明

    • 事件绑定:通过$('#myTable').on('change', 'select[name="freason"]', ...),我们为所有名为freason<select>元素绑定了一个change事件。
    • Ajax请求:当freason的值改变时,会向服务器发送一个GET请求,请求URL是/get_reasons,并将freason的值作为参数传递。
    • 更新下拉框:在成功接收到服务器返回的数据后,会清空当前reason下拉框的所有选项,然后根据返回的数据动态添加新选项。

    这样,每当freason的值发生改变时,只会触发同一行reason下拉框的更新,而不会影响到表格中的其他行。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 6月14日