我正在尝试创建一个模式弹出窗口,该窗口包含一个确认删除按钮,当我在索引视图上按Delete时,该按钮包含您要删除的对象的ID,我用jquery获取并替换了表单采取行动。 我的问题是要替换它,而不仅仅是替换我的操作表单上的占位符ID,而是用http://localhost/project/public/logout之类的东西替换整个路由。
删除index.blade.php上的按钮:
<button type="button" class="btn btn-outline-danger" data-toggle="modal" data-target="#deleteModal" data-id="{{$category->id}}"><i class="far fa-trash-alt"></i> Delete</button>
模态表格:
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST">
@csrf
@method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
jQuery函数,用于替换表单操作属性上的placeholderId:
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('form').attr('action');
modal.find('form').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
结果:
<form action="http://localhost/project/public/logout" method="POST">
预期结果:
<form action="http://localhost/project/public/manager/categories/1" method="POST">
答案 0 :(得分:1)
给提交表单另一个ID,然后在jQuery上通过该ID找到该表单,立即执行,将其gettign作为DOM上的第一个表单,然后退出表单
基本上将id =“ categoriesForm”放在jQuery $(“#categoriesForm”)。submit()
$(document).ready(function() {
$('#deleteModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var placeHolderId = button.data('id');
var modal = $(this);
var action = $('#categoryForm').attr('action');
modal.find('#categoryForm').attr("action", action.replace('placeHolderId', placeHolderId));
});
});
或者您可以做的是在提交表单时捕获,然后阻止默认设置,弹出确认窗口,然后提交
<form action="{{route('categories.destroy', ['id' => 'placeHolderId'])}}" method="POST" id="categoryForm">
@csrf
@method('DELETE')
<button type="button" class="btn" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger" type="submit">Delete</button>
</form>
$(document).ready(function() {
$("#categoryForm").on('submit', function(e) {
e.preventDefault();
var confirmDelete = confirm("Are you sure you want to delete this category!");
if(confirmDelete) {
$(this).submit()
}
})
});