首页 > 解决方案 > 如何通过单击文本提交从循环生成的许多表单之一

问题描述

一个查询返回一个通知数组,这些通知在前端循环。对于数组中的每个项目,我有两个选项:Mark as read, Delete,每个都是文本。目标是通过单击文本来触发表单提交。

正在循环的前端代码是一个带有选项下拉列表的按钮。我希望能够单击文本以提交表单。我学过的 JavaScript 很棘手。我有两种方法可以获得点击响应,但我被卡住了,因为我不知道如何提交表单。

<button class="btn btn-light btn-sm dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Action
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <form action="/notifications/{{ $notification->id }}/edit" method="POST" name="updateNotificationForm" class="update-notification-form">
        @csrf
        {{-- @method('PUT') --}}
        <input type="hidden" name="id" value="{{ $notification->id }}">
        <p class="update-notification pl10">Mark read</p>
    </form>
    <form action="/notifications/delete/{{ $notification->id }}" method="POST" class="delete-notification-form">
        @csrf
        <input type="hidden" name="id" value="{{ $notification->id }}">
        <p class="delete-notification pl10">Delete</p>
    </form>
</div>

前端截图* 在此处输入图像描述

这是Javascript:

方法一:

document.querySelectorAll('.update-notification').forEach(item => {
    item.addEventListener('click', event => {
        console.log("Mark read clicked");

        // submit form
        
    });
});

方法二:

JavaScript 资源

document.addEventListener('click', function (event) {
    if ( event.target.classList.contains('update-notification') ) {
        console.log("Mark read was clicked");

        // submit form
   
    }
}, false);

显示console.log每个方法都链接到数组中的每个元素,但我不知道如何提交表单。

我很感激任何帮助!

标签: javascript

解决方案


解决方案是简单地定位目标本身的父节点并触发提交。

document.querySelectorAll('.update-notification').forEach(item => {
    item.addEventListener('click', event => {
        console.log("Mark read clicked");
         event.target.parentNode.submit();
    });
});

推荐阅读