首页 > 解决方案 > 带有验证和存储 Jquery 的 Laravel 表单添加 html 元素

问题描述

我使用 Laravel,并且我有一个带有 laravel 验证和必填字段的表单(所以当我收到错误时,它总是重新加载所有页面,并且我使用旧刀片标签保留值)。一切都好,但我做了一个按钮来添加一些带有 jquery 的文本框

$(".add-more").click(function(){ 
      var html = $(".copy").html();
      $(".after-add-more").before(html);
    });

    $("body").on("click",".remove",function(){ 
      $(this).parents(".control-group").remove();
    });

当 Laravel 在提交后的每条无效消息处重新加载所有页面时,如何保存旧值和创建的 n-html 元素?谢谢

标签: jquerylaravelvalidation

解决方案


它很简单,你不需要重新加载整个页面,例如用 laravel 的 @include 包含一个元素,表格的内容在另一个刀片文件中,但它被包含了

<table class="table tablesorter ">
    <thead class=" text-primary">
        <tr>
            <th scope="col">ID</th>
            <th scope="col">TIPO</th>
            <th scope="col">fecha</th>
            <th scope="col">Monto</th>
            <th scope="col">Acciones</th>
        </tr>
    </thead>
    <tbody id="table">
        @include('component-table')
    </tbody>
</table>

组件表.blade.php


    <tr>
        <td>hi</td>
        <td>
            test
        </td>
        <td></td>
        <td></td>
        <td class="text-right">

        </td>
    </tr>

现在,您可以创建一个返回此视图的控制器,并在您调用该控制器时仅重新加载表,并将 html 替换为 jquery 的 html() 函数

//on controller 
    public function table()
    {
        return view('component-table.blade.php');
    }
//js
    async function reloadTable(){
        await $.ajax({
            type: "GET",
            url: "{{ route('component-table') }}",
            data: '',
            success: function(response){
                            $('#table').html(response)
                        }
        });
    }

推荐阅读