How do I organize the default submission of forms? [Active for test], organization form submission
In a recently developed project, my part has form verification. I clicked the submit button, but I didn't want him to jump to the page to submit. So after a variety of Baidu, various stackoverflow, and a variety of legs, the following solutions are available:
The key is to prevent the default submission behavior of form submit (). One method uses return false and the other is event. preventDefault (); both methods can be used, but they are different. You need to select one based on your actual situation. What is the difference? I will tell you after reading the article.
First, the code in html is as follows:
1 <! Doctype html> 2
The code in js is as follows:
1 $ ('# myForm'). submit (function (event) {2 if (! $ ('# Name'). val () {3 alert ('name cannot be blank'); 4 event. preventDefault (); 5}; 6 })
When the table name value is blank, a prompt box is displayed to prevent the jump. Code Demo: http://plnkr.co/edit/CZ9TYOMKXheCvq7fMQ7f? P = preview
Of course, you can also use return false to block it. The Code is as follows:
1 $ ('# myForm'). submit (function (event) {2 if (! $ ('# Name'). val () {3 alert ('name cannot be blank'); 4 return false; 5}; 6 })
Code Demo: http://plnkr.co/edit/CZ9TYOMKXheCvq7fMQ7f? P = preview
If you are using an angularjs framework, you only need to add ng-controller, ng-app, and so on to this code.
Finally, return false and event. preventDedault (): If you want to do something else after blocking the form submission, use event. preventDefault (), such as adding a red border to the empty input to remind users, because the code after return false will not be executed. If you don't want to do anything, there is no difference between the two. You are willful!
Red border code:
1 $ ('# myForm'). submit (function (event) {2 if (! $ ('# Name '). val () {3 alert ('name cannot be blank '); 4 event. preventDefault (); 5 items ('your name'your .css ('border-color', 'red'); 6} 7 })
Ps: event. preventDefault (); what is it? Http://www.w3school.com.cn/jsref/event_preventdefault.asp
What are you looking ?! Comment and follow!