Front-end Programming Improvement Tour (17)----jquery forms, tables, and Ajax

Source: Internet
Author: User

from a framework core functional level, the implementation of the selector, Dom operation, events, animation, the function is complete. And any framework written out is applied, so the knowledge of the forms and tables involved in DOM operations, but more biased to the use of practical application skills in the project. The content of the Ajax section is the core of the front-end interaction with the backend.

I. Forms and forms in jquery application

In the actual project, the forms and tables play the data that collects, submits the user input and displays the list respectively. is very important in HTML. Here are some of the knowledge maps:


1. Forms

(1) Single-line text box

The single-line text box function is to get the data in the specified format entered by the user. This involves two-point interaction.


This two-point interaction is reflected in the change of focus and loss of focus, when the focus is taken, the radio box adds a background color, and the content hints are emptied. The background color is removed when the focus is lost, and the content prompt resumes if the content is empty.

The jquery code is as follows:

$ (": Input"). focus (function () {  $ (this). AddClass ("Focus");  if ($ (this). Val () ==this.defaultvalue) {                    $ (this). Val ("");             }}). Blur (function () {$ (this). Removeclass ("Focus"), if ($ (this). val () = = ") {                $ (this). Val (this.defaultvalue);             });

(2) multiline text box

A more important application of a multiline text box is to control the change of the scroll bar. If there is a slide-up command, move the text box scroll bar up 50px. Vice versa.

The jquery code is as follows:

var $comment = $ (' #comment ');//Gets the comment box    $ ('. up '). Click (function () {///Up button to bind the order click event   if (! $comment. Is (": Animated")) {//Determine if the animation $comment.animate ({scrolltop  : "-=50"}, 400);}) $ ('. Down '). Click (function () {///-down button to bind order Click event   if (! $comment. Is (": Animated")) {$comment. Animate ({scrolltop  : "+ =50 "}, 400);});

(3) check box application

The check box is very important for user file management, which mainly involves three functions: Select All, not select, and reverse select. All three of these features involve modifying each check box checked property.

The implementation of the above three function code is as follows:

$ ("#CheckedAll"). Click (function () {     $ (' [Name=items]:checkbox '). each (function () {     this.checked = true;     })}); Do not select     $ ("#CheckedNo"). Click (function () {    $ (' [Name=items]:checkbox '). each (function () {    this.checked= false;    }); }); Counter-select     $ ("#CheckedRev"). Click (function () {  $ (' [Name=items]:checkbox '). each (function () {//) directly using the JS native code, Simple and practical this.checked=!this.checked;  });

implementing these functions is only the first step, the common Select all/all is a button, when the list option is selected All, the selection must be selected. So there is a two-way communication between the Select and list items. In code, two-way control must be achieved: that is, in addition to modifying the state of itself, it is necessary to determine whether another State needs to be modified.

The following code uses a temporary variable record to determine whether to select all:

Select All        $ ("#CheckedAll"). Click (function () {            //All checkboxes follow the All-selected checkbox.            var self =this;            $ (' [Name=items]:checkbox '). each (function () {            this.checked=self.checked;            });        });        $ (' [Name=items]:checkbox '). Click (function () {            ///define a temporary variable to avoid reusing the same selector to select elements in the page to improve program efficiency.            var $tmp = $ (' [Name=items]:checkbox ');            Filter the selected check box by using the filter method. and assign values directly to Checkedall.            $ (' #CheckedAll '). attr (' checked ', $tmp. length = = $tmp. Filter (': Checked '). length);        });

(4) drop-down box application

The drop-down box is mainly focused on the two columns, and the drop-down is toggled before the drop-down box, mainly related to the option tag selected property used to filter the selected items, in addition to Dom movement. Mainly involves moving the selected, all move, double-click Move. Note Double-click Move takes the context filter to move the item.

The code is as follows:

$ (' #add '). Click (function () {///Get the selected option, delete and append to the other $ (' #select1 option:selected '). AppendTo (' #select2 ');}); $ (' #add_all '). Click (function () {//Get all options, delete and append to the other $ (' #select1 option '). AppendTo (' #select2 ');}); $ (' #select1 '). DblClick (function () {///bind double-click event//Get all options, delete and append to the other $ ("option:selected", this). AppendTo (' #select2 '); Append to each other});

(5) Form Verification

Form validation is the most common, requires real-time user input information, the use of lost focus judgment method, in order to display in real time, while in KeyUp and focus events, both trigger the blur method, while avoiding the browser default blur event.

The code is as follows:

 $ (' Form:input '). blur (function () {var $parent = $ (this). parent (); $parent. Find (". Formtips"). Remove ();//Verify the user name if ($ (                        This). is (' #username ')) {if (this.value== "" | | This.value.length < 6) {var errormsg = ' Please enter a user name of at least 6 digits. '; $parent. Append (' <span class= ' formtips onError ' > ' +errormsg+ ' </span> ');}    else{var okmsg = ' input correct. '; $parent. Append (' <span class= ' formtips onsuccess ' > ' +okmsg+ ' </span> ');} }//Verify the message if ($ (this). is (' #email ')) {if (this.value== "" | | (this.value!= "" &&!/[email protected]+\. [A-za-z]  {2,4}$/.test (This.value))) {var errormsg = ' Please enter the correct e-mail address. '; $parent. Append (' <span class= ' formtips onError ' > ' +errormsg+ ' </span> ');}  else{var okmsg = ' input correct. '; $parent. Append (' <span class= ' formtips onsuccess ' > ' +okmsg+ ' </span> ');} }}). KeyUp (function () {$ (this). Triggerhandler ("blur");}). Focus (function () {$ (this). Triggerhandler ("blur");}); /end Blur

2. Forms

(1) Expand close

The expansion of the table closed, that is, to expand the switch off two states, the previous animation said the toggle method can toggle the display of hidden, here through the control of the same sibling node switch off display.

The code is as follows:

$ (' tr.parent '). Click (function () {   //Get the so-called parent row $ (this). Toggleclass ("selected")   //Add/Remove highlight. Siblings ('. Child_ ' +this.id). Toggle ();  Hide/show the so-called child rows}). click ();

(2) Content screening

For the content filter of a list, the filter method is used primarily to filter the list items that contain the specified content. Filter when KeyUp.

The code is as follows:

$ ("#filterName"). KeyUp (function () {      $ ("Table Tbody tr"). Hide (). Filter (": Contains ('" + ($ (this). Val ()) + "')"). Show ();   }). KeyUp ();

two. jquery and Ajax

The biggest meaning of Ajax is that changing the past and the end of the data need full page refresh to get the page content, you can partially refresh the page. It works by implementing an AJAX engine on the client that asynchronously enables user actions and server responses.

The jquery strategy lists some of the big problems with Ajax, but it doesn't seem to affect the wide range of AJAX applications. As a front-end developer, the biggest drawback of Ajax is the problem of asynchronous responses. Asynchronous responses require developers to stay focused on timing execution logic at all times, and often many problems are here.

jquery provides a very simple Ajax operation that replaces the complex, redundant operation of native code, making AJAX applications simple. The following is a Yue Timor knowledge map of this part of Ajax:


1. Ajax Methods of Operation

As the above knowledge shows, the AJAX approach can be divided into three layers, from simple to complex, from top to bottom. The second layer is most commonly used. The bottom of these Ajax methods is the encapsulation of native Ajax methods. However, the application scenario is slightly different, the more the upper application scenario is more targeted, the less flexible. The bottom $.ajax () is flexible enough to be more complex to configure.

Each Ajax action method involves a parameter with 3 URLs (request address), data (sent to the server), callback (callback when the request is completed).

The most commonly used two are $.get () and $.post (), respectively, corresponding to the Ajax operation of the GET request mode and the POST request mode, the two methods differ three points:


The $.getscript () and $.getjson () Two Ajax methods are for dynamic load scripts and JSON file scene settings respectively.

The $.ajax () method is the lowest-level construct of the above Ajax operations method, which can be substituted for the above method.

2. Method of parameter serialization

The first part of this article mentions that the form is the way to get user data, the user fills out the form, and sends it to the server to collect the user form data. It is cumbersome to take data.

The method of parameter serialization is the automatic serialization of form data for AJAX requests.

Serialize () is used to serialize the contents of a DOM element into a string:


Serializearray () is used to serialize DOM elements and return JSON-formatted data:


The $.param () method is used to serialize array or object key-value pairs:


3.ajax Request Control Method

Here are two methods: The Ajaxstart method is triggered when the AJAX request starts, and the Ajaxstop method is triggered at the end of the AJAX request. Often used to enhance the user experience and add loading hints to the user.

Examples of Use:

$ ("#send"). Click (function () {  $ ("#resText"). Load ("test.html");  })  $ ("#resText"). Ajaxstart (function () {  Console.log ("Ajax has Started");  });  $ ("#resText"). Ajaxstop (function () {  Console.log ("Ajax has stopped");  });


Front-end Programming Improvement Tour (17)----jquery forms, tables, and Ajax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.