You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel项目点击SweetAlert取消按钮仍提交表单如何解决?

修复方案

核心问题原因

  1. 你在checkbox标签上写的内联onchange="this.form.submit();"会在复选框状态变更时直接触发表单提交,你绑定的click事件中的e.preventDefault()只能阻止点击事件的默认行为,无法拦截内联onchange事件的提交逻辑。
  2. 旧版判断逻辑有误:当前主流版本的SweetAlert回调返回的是结果对象,不是布尔值,哪怕用户点击了"No",回调拿到的参数也是非空对象,你的if(isConfirm)判断会永远成立,导致误提交。

具体修改步骤

第一步:移除表单内联的onchange提交逻辑

修改后的表单代码如下:

<form id="myForm" action="{{ route('acceptWallet') }}" method="POST">
    @csrf
    <input type="checkbox" id="btn-submit" name="wallet_checked">
</form>

第二步:调整JS交互逻辑

直接监听复选框的change事件,根据SweetAlert的返回结果判断是否提交表单,点击取消时还会自动还原复选框状态:

$(document).on('change', '#btn-submit', function(e) {
    e.preventDefault();
    const currentChecked = $(this).prop('checked');
    const targetForm = $('#myForm');
    
    swal({
        title: "Attention!",
        text: "Are you sure you want to make this transaction",
        type: "warning",
        allowEscapeKey: false,
        allowOutsideClick: false,
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        showLoaderOnConfirm: true,
        closeOnConfirm: false
    }).then((result) => {
        // 兼容不同版本SweetAlert的返回值判断
        const isConfirmed = result.isConfirmed !== undefined ? result.isConfirmed : result === true;
        if (isConfirmed) {
            targetForm.submit();
        } else {
            // 取消操作时还原复选框状态
            $(this).prop('checked', !currentChecked);
        }
    });
});

内容的提问来源于stack exchange,提问作者user16723850

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:12:00