首页 > 解决方案 > 如何传递值以形成动作 laravel

问题描述

我有一个表格可以查看包含名称和 id 的数据,当单击编辑按钮以在同一页面中以表格形式显示此数据以进行编辑时,我想要对其进行编辑,这是在 JS 中制作的

我传递详细信息的编辑按钮

<button onclick="openForm2('{{ $t->name }}');"> edit </button>

JS函数

    function openForm2($val) {
        document.getElementById("name").value = $val;
    }

要更新的表格

    <form method="post"   action="{{route('type.update',$t->id)}}"
                class="form-container">
        <h1>edit type</h1>
        @csrf
        {{ method_field('PATCH') }}

        <input type="text"
               name="name"
               id="name"
               required>

        <button type="submit" class="btn">edit</button>
    </form>

问题是表格的动作

action="{{route('type.update',$t->id)}}

如何传递被点击元素的id?

标签: javascriptlaravel

解决方案


如果你的路由 'type.update' 端点是 '/type/{id}' 那么 Laravel Blade 将渲染

{{route('type.update', $t->id)}} 作为' http://your-url.com/type/5 '。

如果您希望 JavaScript 设置 id,您需要更新操作并将操作设置为“ http://your-url.com/type/5 ”。

//Blade
<button onclick="openForm2('{{ $t->name }}', '{{route('type.update', $t->id)}}');"> edit </button> //Pass the route as action to JS function

<form method="post" action="{{route('type.update',$t->id)}}" class="form-container" id="my-form"> //Set id to "my-form" used by JS

//JS
function openForm2(type, action) {

  document.getElementById("name").value = val;

  var form = document.getElementById("my-form");

  form.action = action; // Update your form with the action containing your new id used for submit

}

推荐阅读