[英]How do I cancel a button click event in JavaScript?
I tried doing it two different ways:我尝试了两种不同的方式:
$(document).ready(function()
{
$('input[type=button]').on('click', function(evt){
if ($(this).val() == 'Close')
return true;
var totalHours = 999; // here I am computing a total number of hours but that is irrelevant to my question
var reportedTotalHours = parseFloat($("#TotalHours").text());
var difference = Math.abs(totalHours - reportedTotalHours);
if (difference >= 0.25) // discrepancy must be less than a quarter hour
{
alert("Total of hours for each activity must equal " + reportedTotalHours + ".");
evt.preventDefault();
return false;
}
return true;
});
});
return false;
should be cancelling the button click, as should evt.preventDefault();
应该取消按钮点击,就像
evt.preventDefault();
, but neither of them is working for me. ,但他们都不为我工作。 What happens when the button is clicked is the form is submitted, but I want to prevent the form from being submitted until the discrepancy in hours is less than 0.25.
单击按钮时会发生什么是提交表单,但我想防止提交表单,直到小时差异小于 0.25。
Try changing your input[type=button] to a button tag.尝试将 input[type=button] 更改为按钮标签。 Then submit your form in your onclick callback when the conditions are right.
然后在条件合适时在您的 onclick 回调中提交您的表单。
In some browsers an input[type=button] element will submit a form if there's no input[type=submit] element.在某些浏览器中,如果没有 input[type=button] 元素,则 input[type=button] 元素将提交表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.