Front-end form operation based on JQuery

Keywords: Javascript JQuery less Attribute

Jquery's front-end form operation:

jquery provides a good way to encapsulate, and can save a lot of trouble in some basic operations. Among them, the data submission of form form is the most frequent and most common way of data exchange. Therefore, some problems need to be solved in the front-end processing of form form (data acquisition, form validation, submission validation).

Firstly, several methods are introduced.


(1) Event method for jquery:.submit() Form submission event

Usage 1: $ele.submit() binds the $ele element without any parameters, which is generally used to specify triggering an event, and is less used.

example

1 <div id="test">Click trigger<div>
2 $("ele").submit(function(){
3     alert('Triggers a specified event')
4 })
5 $("#text").click(function(){
6      $("ele").submit()  //Specify trigger events 
7 });

Usage 2: $ele. submit (eventObject). Bind the $ele element, and each time the $ele element triggers a click, it executes a callback handler function, which can do a lot of manipulation for event feedback.

Example

1 <form id="target" action="destination.html">
2   <input type="submit" value="Go" />
3 </form>
4 $("#target").submit(function() { //Binding submission form trigger
5     //this point from element 
6 });

Usage 3: $ele. submit ([eventData], handler (eventObject) is used in the same way as method 2, but it can accept a data parameter, which is used to solve the problem of data transmission in different scopes.

Example:

1 <form id="target" action="destination.html">
2   <input type="submit" value="Go" />
3 </form>
4 $("#target").submit(11111,function(data) { //Binding submission form trigger
5     //data => 1111 //Data data passed
6 });

By binding submit events on < form > elements, developers can monitor the user's submission behavior, which is triggered when the type attribute in the input tag is submit.

Note: Form elements have default submission behavior. If submit is used to submit, browser default behavior needs to be prevented beforehand. The traditional js processing method is to call the default event blocking method e.preventDefault() to prevent the default event. In Jquery, return false can be used directly in the function to prevent the default event. Generally, return true is invoked after the logic is used to restrict and detect the front form correctly. Otherwise, return false is used as follows

 

1 $("#target").submit(function(data) { 
2    return false; //Prevent default commit behavior
3 });

 

(2) serialize() method -- serialize form values

The serialize() method creates a URL-encoded text string by serializing form values. You can select one or more form elements (such as input and/or text boxes) or form elements themselves. The serialized values can be used in the URL query string when generating AJAX requests.

Example:

<form id="forms" action="ajax" method="post">
     <div class="box">
            <table>
             <tr>
               <td>Full name</td>
               <td><input name="username" type="text"></td>
             </tr>
             <tr>
               <td>Gender</td>
              <td><input name="sex" type="text"></td>
             </tr>  
             <tr>
               <td>Age</td>
               <td><input name="age" type="text"></td>
             </tr>  
             <tr>
               <td>Cell-phone number</td>
               <td><input name="phone" type="text"></td>
             </tr>    
             <tr><td><button type="submit">Submission</button></td></tr>
           </table>   
     </div>
  </form>
  <script type="text/javascript">
     $(function(){
         $("#forms").submit(function(){
             alert($("#forms").serialize());
             return false;
         })
     })
  </script>

JQuery's form plug-in (validation Plugin here)

First, download validate files from the official website. Generally, personal editors only need to download validate files. jquery.validete.min.js File is OK. When you use it, you first introduce the jquery configuration file and then introduce the file.

Generally, client-side verification includes two points. The first is to reduce the pressure of the server. Some data validity is filtered through the front end without additional rewriting in the background. The second is a friendly customer experience, coupled with ajax, which can avoid the vicious circle of long information input submission-rejection-filling-resubmitting.

Before using validate, two of these concepts are introduced:

Method: Specific verification logic is encapsulated as a separate method, such as email method, which checks whether the input character meets eamil format.

rule: Refers to the association of elements with validation methods, such as specifying an input tag, which specific methods need to be used for it (the method above)

The core method in validate: valiadate ()

The format used is:

<form id="test1">
   <input type="text" name="username" />
</form>
<script>
    var validator1;
    $(document).ready(function () {
      $("#test1").validate({
            rules: {
                username: {
                    required: true,//Call the method method method and limit it to mandatory
                    minlength: 2,
                    maxlength: 10
                }
            },//rules rule, where "username" needs to be consistent with the value of the name attribute in the input form
            messages: {
                username: {
                    required: 'enter one user name',
                    minlength: 'User name should not be less than 2 characters',
                    maxlength: 'User names should not exceed 10 characters',
                    remote: 'user name does not exist'
                }
             }//end messages  
        });
    });
</script>

 

Introduction of main method s:

method Basic method
Method name: Introduction (function)
required Boolean value, true/false, when true, is expressed as mandatory
remote Remote validation, combined with ajax, compares with back-end data, and uses "{}" to place attributes
minlength Minimum length, length of input data
maxlength Maximum length, length of input data
rangelength Limit the length range of the input, set an interval, the number of input values can not be less or more than
min Minimum Value Limitation of Input Numbers
max Maximum Limitation of Input Numbers
range Interval Limitation of Input Numbers
email Does the input data conform to the email format?
url Does the information entered match the address (including http://)
date Is the input information in a standard date format?
dateISO Does the input information follow ISO standards?
number The input information must be a number
digits The number entered must be an integer
equalTo Is the value equal to the value of another element to verify the secondary password

 

In particular, the remote method and equalTo method are introduced.

 

remote is mainly used for instantaneous interaction with the background, information judgment, mostly for the registration form user name anti-duplication processing, asynchronous transmission to the background using ajax, the background to complete the data judgment. The main formats are as follows:

        username{          

                    required: true,
                    minlength: 2,
                    maxlength: 10,
remote: "server-side URL address"//By default, a get request is sent to the background with the content "url? usernmae=value ", the return value is only true/false, false triggers the prompt information, true does not

           }

 

 

The equalTo method is mostly used to verify the second password in registration and encryption (i.e. to ensure the same input twice). The main format is as follows:

EquaTo: "Adding Element Objects to Make the Same Judgment"

Example:

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>jQuery Form Validation</title>
 6     <link rel="stylesheet" href="css/style.css"/>
 7 </head>
 8 <body>
 9 <form id="demoForm" action="checkTest" method="post">
10     <fieldset>
11         <legend>User login</legend>
12         <p id="info"></p>
13 
14         <p>
15             <label for="username">User name</label>
16             <input type="text" id="username" name="username"/>
17         </p>
18 
19         <p>
20             <label for="password">Password</label>
21             <input type="password" id="password" name="password"/>
22         </p>
23 
24         <p>
25             <label for="confirm-password">Confirm password</label>
26             <input type="password" id="repassword" name="repassword"/>
27         </p>
28 
29         <p>
30             <input type="submit" value="Sign in"/>
31         </p>
32     </fieldset>
33 </form>
34 
35 <script src="Js/jquery.js"></script>
36 <script src="Js/jquery.validate.min.js"></script>
37 <script>
38     var validator1;
39     $(document).ready(function () {
40        $("#demoForm").validate({
41             debug: true,
42             rules: {
43                 username: {
44                     required: true,
45                     minlength: 2,
46                     maxlength: 10
47                 },
48                 password: {
49                     required: true,
50                     minlength: 2,
51                     maxlength: 16
52                 },
53                 repassword: {
54                     equalTo: "#password"
55                 }
56             },
57             messages: {
58                 username: {
59                     required: 'enter one user name',
60                     minlength: 'User name should not be less than 2 characters',
61                     maxlength: 'User names should not exceed 10 characters',
62           
63                 },
64                 password: {
65                     required: 'Please input a password',
66                     minlength: 'Password must not be less than 2 characters',
67                     maxlength: 'Password cannot exceed 16 characters'
68                 },
69                 repassword: {
70                     equalTo: "Two inconsistencies in password input"
71                 }
72 
73             },
74 
75           
76         }); 
77 
78          $("#demoForm").submit(function (data) {
79             console.log(data);
80             if($("#demoForm").valid())//Check data for errors
81              {
82                console.log($("#demoForm").valid());
83                $.post("checkTest?"+$("#demoForm").serialize()); 
84              } 
85             else{
86                alert("Please confirm the information!");
87                return false; 
88            } 
89          }); 
90     });
91 </script>
92 Validation Plugin
93 </body>
94 </html>
 1 @WebServlet("/checkTest")
 2 public class checkTest extends HttpServlet {
 3     private static final long serialVersionUID = 1L;
 4        
 5     /**
 6      * @see HttpServlet#HttpServlet()
 7      */
 8     public checkTest() {
 9         super();
10         // TODO Auto-generated constructor stub
11     }
12 
13     /**
14      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
15      */
16     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         // TODO Auto-generated method stub
18         response.setCharacterEncoding("utf-8");
19         String username = request.getParameter("username");
20         String password = request.getParameter("password");
21         System.out.println(username+password);
22         response.getWriter().print("Success");
23     }
24 
25     /**
26      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
27      */
28     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
29         // TODO Auto-generated method stub
30         doGet(request, response);
31     }
32 
33 }

Posted by uatec on Sun, 19 May 2019 06:47:52 -0700