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

表单内执行JavaScript计算的按钮意外触发表单提交问题咨询

问题根因

根据HTML规范,位于<form>标签内的<button>元素如果未显式指定type属性,浏览器默认会将其识别为submit类型按钮,点击后会触发表单提交的默认行为,和绑定的自定义点击逻辑无关。


解决方案

方案1:显式指定按钮为普通按钮(最推荐)

直接给两个按钮添加type="button"属性即可取消默认提交行为,无需修改现有JS逻辑,改动最小兼容性最好。修改后的表单代码如下:

@Html.EditorFor(model => model.Miles, new { htmlAttributes = new { @class = "form-control", @id = "number" } })
<button type="button" onclick="roundTrip()">Round Trip?</button>&nbsp;
<button type="button" onclick="updatedPrice()">Update Price</button>

@Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control", @id = "price" } })

方案2:在点击事件中阻止默认行为

如果不想修改按钮标签属性,也可以通过阻止事件默认行为实现效果,有两种可选实现:

  • 实现方式1:在onclick绑定末尾增加return false
    按钮代码修改为:
    <button onclick="roundTrip();return false;">Round Trip?</button>&nbsp;
    <button onclick="updatedPrice();return false;">Update Price</button>
    
  • 实现方式2:在JS函数内调用事件阻止方法
    修改后的JS代码如下:
    function updatedPrice(e) {
        e.preventDefault();
        var price = $("#number").val() * @calcMiles;
        var calPrice = price.toFixed(2)
        $("#price").val(calPrice);
    }
    
    function roundTrip(e) {
        e.preventDefault();
        var calc = $("#number").val() * 2;
        $("#number").val(calc);
    }
    
    对应按钮绑定需要传入事件对象:
    <button onclick="roundTrip(event)">Round Trip?</button>&nbsp;
    <button onclick="updatedPrice(event)">Update Price</button>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:39:04