[英]java script submitting form after validation
I have a little problem. 我有一点问题。 I have a form, and my js validate it.Then, I need to submit the form if validation is success , and prevent submitting if the validation is not success. 我有一个表单,我的js对其进行了验证,然后,如果验证成功,则需要提交表单,如果验证不成功,则阻止提交。 I tried to use addEventListener (submit,function). 我试图使用addEventListener(提交,功能)。 But I don`t know how to do this. 但是我不知道该怎么做。 What is the best way to make this without using JQuery? 不使用JQuery的最佳方法是什么?
Call your function using onsubmit event: 使用onsubmit事件调用函数:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm()
{
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
Assuming you have a form with a name, you can call submit from javascipt or not call it if validation is not passed: 假设您有一个带有名称的表单,则可以从javascipt调用Submit,或者如果未通过验证则不调用它:
//HTML
<form name="myform">
......
</form>
//JS after validation checks, you set validation_errors = true or false
if validation_errors:
document.forms["myform"].submit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.