简体   繁体   English

如果发现错误,防止提交 HTML 表单

[英]Prevent HTML Form From Submitting If Error Found

I have a form where the user is supposed to enter a number, and some javascript that validates it.我有一个表单,用户应该输入一个数字,以及一些验证它的 javascript。 I have the following code for my submit button:我的提交按钮有以下代码:

<input onclick="validate()" type="submit" value="Submit">
<p id="displaytext"></p>

and the javascript to go with it:和 javascript 到 go :

function checkInt() {
    var amount, text;
    amount = document.forms["formname"]["amount"].value;

    if (isNaN(amount)) {
        text = "amount must be an integer";
        document.getElementById("displaytext").innerHTML = text;
    }
}

My javascript code works correctly and displays the message, the problem I am having is that I need to form to not submit when the input is not a number.我的 javascript 代码正常工作并显示消息,我遇到的问题是当输入不是数字时我需要形成不提交。 I need to to display "amount must be an integer" and stay on that page.我需要显示“金额必须是整数”并留在该页面上。 What I have now will quick display that amount is not an integer, but when go on and submit the form anyway.我现在将快速显示该金额不是 integer,而是当 go 开启并提交表单时。

If this is a form, you can use event.preventDefault() and handle error output message in your function.如果这是一个表单,您可以使用event.preventDefault()并处理 function 中的错误 output 消息。

https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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