问题描述
我想对一些文本框条目运行 JavaScript 用户验证.
I want to run JavaScript user validation on some textbox entries.
我遇到的问题是我的表单具有转到我们网站内的新页面的操作,并且 onsubmit
属性从不运行 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.
是否有更好的解决方案,或者使用以下代码的解决方案:注意:如果您将操作切换到 checkRegistration()
.
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()
.
这只是同时运行 action 和 JavaScript 的问题.
It is merely an issue with running both action and JavaScript.
<form name="registerForm" action="validate.html" onsubmit="checkRegistration()" method="post">
<!-- Textboxes are here -->
<!-- And the submit button -->
</form>
推荐答案
您应该通过在 onsubmit 回调.
You should stop the submit procedure by returning false on the onsubmit callback.
<script>
function checkRegistration(){
if(!form_valid){
alert('Given data is not correct');
return false;
}
return true;
}
</script>
<form onsubmit="return checkRegistration()"...
这里有一个完整的示例.表单只有在input输入google时才会提交,否则会返回错误:
Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:
<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>
这篇关于HTML 表单操作和提交问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!