表单内执行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> <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> <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> <button onclick="updatedPrice(event)">Update Price</button>
内容的提问来源于stack exchange,提问作者Scott Purtan
相关产品推荐
相关产品推荐

