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

如何实现仅在点击Save按钮时触发jQuery表单验证

解决表单提交事件触发所有按钮验证的问题

你遇到的问题根源很简单:你的Cancel和List按钮没有指定type属性,在HTML规范里,<button>元素默认的type是submit——也就是说,点击这两个按钮时,它们会和Save按钮一样触发表单的submit事件,自然就会触发你绑定的验证逻辑了。

这里有两种简单的解决方案,推荐第一种,因为更符合HTML语义,代码也更清晰:

方案一:明确按钮的type属性

把Cancel和List按钮的type设置为button,这样它们就不会触发表单提交,只会响应你单独绑定的点击事件:

修改后的HTML按钮代码:

<button type="submit" class="btn btn-primary" id="save" name="save">Save</button>
<button type="button" class="btn btn-warning" id="cancel" name="cancel">Cancel</button>
<button type="button" class="btn btn-success" id="list" name="list">List</button>

给Cancel和List绑定独立的点击逻辑:

// Cancel按钮逻辑:比如返回上一页或者清空表单
$("#cancel").click(function() {
    window.history.back();
});

// List按钮逻辑:比如跳转到列表页面
$("#list").click(function() {
    window.location.href = "list.php"; // 替换成你的列表页面路径
});

方案二:在submit事件中判断触发按钮

如果你不想修改按钮的type,可以在表单的submit回调里判断是哪个按钮触发了提交,只有当按钮是Save时才执行验证:

$("form").submit(function (e) {
    // 获取触发提交的按钮
    const clickedButton = $(e.originalEvent.submitter);
    
    // 如果不是Save按钮,执行对应逻辑并阻止默认提交(或根据需求调整)
    if (clickedButton.attr("id") !== "save") {
        e.preventDefault();
        if (clickedButton.attr("id") === "cancel") {
            window.history.back();
        } else if (clickedButton.attr("id") === "list") {
            window.location.href = "list.php";
        }
        return;
    }

    // 以下是你原来的验证逻辑
    let errorMessage = "";
    if ($("#surname").val() === "") {
        errorMessage += "Please input a surname.<br>"
    }
    if ($("#name").val() === "") {
        errorMessage += "Please input a name.<br>"
    }
    if ($("#address").val() === "") {
        errorMessage += "Please input an address.<br>"
    }
    if ($("#email").val() === "") {
        errorMessage += "Please input an email address.<br>"
    }
    if (!$("#male").prop('checked') && !$("#female").prop('checked')) {
        errorMessage += " Please input a gender.<br>";
    }
    if ($("#telephone").val() === "") {
        errorMessage += "Please input a telephone number.<br>"
    }

    if (errorMessage !== "") {
        $("#error").html('<div class="alert alert-danger" role="alert"><p>Please fill your form:</p>' + errorMessage + '</div>');
        e.preventDefault(); // 阻止表单提交
        return false;
    } else {
        return true;
    }
});

额外提醒

别忘了你已经在做的服务端验证是必须的——客户端验证只是提升用户体验,很容易被绕过,所以PHP端的验证一定要保留,确保数据的安全性和合法性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 12:18:14