如何阻止表单提交?支持已选收据文件后取消上传
问题解决方法
核心问题
你的取消按钮(CancelSubmission)未指定type="button",在表单内默认是submit类型,点击会直接触发表单提交;另外移除事件监听的写法错误,无法正确取消监听。
步骤1:修正取消按钮的HTML
给取消按钮加上type="button",彻底避免它触发表单提交:
<button class="btn btn-secondary" data-bs-dismiss="modal" id="CancelSubmission" type="button">Cancel</button>
顺便把模态框的关闭按钮也加上type="button",防止误触提交:
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
步骤2:修复JavaScript的事件监听逻辑
把取消按钮的回调函数改成命名函数,这样移除监听时能精准匹配:
let ApprovePayment = document.getElementById('uploadReceiptButton') if (ApprovePayment) { let CancelConfirmation = document.getElementById('CancelSubmission') // 命名回调函数,方便后续移除 function cancelSubmitHandler(event) { event.preventDefault(); } if (CancelConfirmation) { CancelConfirmation.addEventListener('click', cancelSubmitHandler); } ApprovePayment.addEventListener('click', ApprovePaymentFunction); function ApprovePaymentFunction(event) { event.preventDefault(); var receiptUploadForm = document.getElementById('receiptUploadForm') Swal.fire({ title: 'Are you sure?', text: 'Confirm that the correct Receipt is sent to the Applicant', icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes!' }).then((result) => { // 用命名函数移除监听 if (CancelConfirmation) { CancelConfirmation.removeEventListener('click', cancelSubmitHandler); } if (result.isConfirmed) { receiptUploadForm.submit(); } }); } }
说明
- 按钮在表单内的默认类型是
submit,必须显式设为button才会只执行关闭模态框的动作。 removeEventListener必须传入和添加监听时完全相同的函数引用,匿名函数无法被识别,所以要改成命名函数。
内容的提问来源于stack exchange,提问作者Jonas
相关产品推荐
相关产品推荐

