简体   繁体   中英

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(); , 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.

Try changing your input[type=button] to a button tag. Then submit your form in your onclick callback when the conditions are right.

In some browsers an input[type=button] element will submit a form if there's no input[type=submit] element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM