【问题标题】:How to solved always looping select option value from ajax如何解决总是从ajax循环选择选项值
【发布时间】:2021-11-08 17:05:13
【问题描述】:

我有一个数据,当我更新数据时(使用模式),选择选项正常工作

当我关闭模式并再次单击编辑按钮时,选择选项有问题:

这是我的编辑模式 ajax:

// Function for edit modal plan schedule
    $('body').on('click', '.editPlanSchedule', function() {
        var Item_id = $(this).data('id');
        $.get("/quotation/getEditPlanSchedule" + '/' + Item_id, function(data) {
            console.log(data['product_plan']);
            $('.modal-title-edit').html("Edit Plan Schedule Item");
            $('#saveBtn').val("Update");
            $('#updatePlanSchedule').modal('show');
            $('#id').val(data['data'].id);
            $('#qno').val(data['data'].qno);
            $('#b_amount').val(data['data'].b_amount);
            // $('#product_plan_edit').val(data.product_plan);
            
            data['product_plan'].forEach(function(item, index) {
                
                $('#product_plan_edit').append($('<option>', {
                    id: item.id,
                    value: item.productplanID,
                    text: item.productplanID
                }));
                
                if(data['data'].product_plan == item.productplanID){
                    $('#'+item.id).attr('selected',true);
                }
            });

        })
    });

这是来自控制器的方法:

public function getEditPlanSchedule($id)
{
    $item['data'] = QuotationPlanSchedule::find($id);
    $item['product_plan'] = ProductPlan::orderby('id', 'asc')->get();
    return response()->json($item);
}

【问题讨论】:

    标签: javascript ajax laravel dom


    【解决方案1】:

    要么 .empty 容器,要么不使用 append(更适合 DOM 更新)

    我对您使用data['data'].product_plan 测试ID 感到有些困惑。无论如何你都能看到原理

    $('#product_plan_edit').html(
      data['product_plan'].map(item => `<option value="${item.productplanID}">${item.productplanID}</option>`).join('')
    );
    $('#product_plan_edit').val(data['data'].product_plan); // select item.productplanID === data['data'].product_plan
    

    【讨论】:

      【解决方案2】:

      您必须在再次添加之前清除所有选项:

      $("#product_plan_edit").empty();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-09
        • 2016-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多