简体   繁体   English

HTML 表单操作和提交问题

[英]HTML form action and onsubmit issues

I want 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 onsubmit attribute 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 are here -->
    <!-- And the submit button -->
</form>

You should stop the submit procedure by returning false on the onsubmit callback.您应该通过在onsubmit回调中返回 false 来停止提交过程。

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

<form onsubmit="return checkRegistration()"...

Here you have a fully working example.这里有一个完整的示例。 The form will submit only when you write google into input, otherwise it will return an 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>

尝试

onsubmit="return checkRegistration()"

尝试:

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

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

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