Home > Article > Web Front-end > Introduction to how JavaScript implements code that prevents form submission
This article mainly introduces the JavaScript method to prevent form submission. Through code examples, it explains the things that need to be paid attention to in preventing form submission, as well as the difference between onSubmit and check(). Friends who need it can refer to it
<body> <form action="clock.html" method="post" onsubmit="return checkLength()"> <p>name:<input type="text" name="user" id="user"></p> <input type="submit" id="submit" name="submit"> </form> </body> </html>
html page.
The first method: Use the default event blocking mechanism of event, obtain the submit element after the page is loaded, and then register the click response function for submit, with the parameter being the event event.
After the user clicks submit to trigger the response function, directly event.preventDefault(); prevents the default event from form jump.
Second method: Add the attribute checkLength()" under the attribute onsubmit="return checkLength()" under the form tag or the attribute checkLength()" under the input tag with id="submit"
function Prevent form submission return false;
Prevent the code in the function from executing downward return;
The following are two events of
##1.form
submit, submit the form. If you call this function directly, the form will be submitted directly
onSubmit, which will be triggered first when the submit button is clicked. Then trigger the submit event. If it is not controlled, it will return true by default, so the form can always be submitted.
Use document.myform.name.value in JS to get each user input and verify it. When it is completely passed, TRUE is returned, otherwise false is returned.
3. Page code implementation/*
<form name="testform" action="hello.html" method="post" onSubmit="return check();">
<input type="text" name="name">
<input type="submit" value="提交">
</form>
*/
4. JS implementation
function check(){
if (document.testform.name.value=="admin") {
alert("姓名不正确");
return false;
}
else{
return true;
}
}
Note
When writing onSubmit, never write: "check()", this is used as a test The form will not be submitted if it cannot pass
The above is the detailed content of Introduction to how JavaScript implements code that prevents form submission. For more information, please follow other related articles on the PHP Chinese website!