HTML 表单操作和提交问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16262797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:57:58  来源:igfitidea点击:

HTML form action and onsubmit issues

javascripthtmlformsactiononsubmit

提问by James Brown

I am wanting to run javascript user validation on some textbox entries.

我想对一些文本框条目运行 javascript 用户验证。

The problem I'm having is that my form has the action of going to a new page within our site, and the onsubmitattribute never runs the javascript function.

我遇到的问题是我的表单具有转到我们网站内的新页面的操作,并且该onsubmit属性从不运行 javascript 函数。

Is there a better solution, or one that works with the following code: NOTE: the javascript file is written correctly and works if you switch the action to checkRegistration().

是否有更好的解决方案,或者使用以下代码的解决方案: 注意:javascript 文件编写正确,如果您将操作切换到checkRegistration().

It is merely an issue with running both action and javascript.

这只是同时运行 action 和 javascript 的问题。

<form name="registerForm" action="validate.html" onsubmit="checkRegistration()" method="post">
    <!-- textboxes here -->
    <!-- and submit button -->
</form>

回答by s3m3n

You should stop submit procedure by returning false on onsubmitcallback.

您应该通过在onsubmit回调中返回 false 来停止提交过程。

<script>
function checkRegistration(){
    if(!form_valid){
        alert('Given data is not correct');
        return false;
    }
    return true;
}
</script>
<form onsubmit="return checkRegistration()"...

UPDATE:

更新:

here you have fully working example, form will submit only when you write google into input, otherwise it will return error:

在这里,您有完整的示例,表单仅在您将 google 写入输入时才会提交,否则将返回错误:

<script>
function checkRegistration(){
    var form_valid = (document.getElementById('some_input').value == 'google');
    if(!form_valid){
        alert('Given data is incorrect');
        return false;
    }
    return true;
}
</script>
<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google..<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

回答by Arun P Johny

Try

尝试

onsubmit="return checkRegistration()"

回答by Hiren Siddhpura

try:

尝试:

onsubmit="checkRegistration(event.preventDefault())"