JQuery operations on forms, jQuery form operations

Source: Internet
Author: User

JQuery operations on forms, jQuery form operations

Form components: Form tags, form fields, and form buttons

<Form> <fieldset> <legend> <label> <input> <textarea>

1. Single-line text box -- get and lose focus change style

When the text box gets the focus, its color changes. If the focus is lost, it is restored to the original style. You can use the pseudo class selector in css to implement this function.

CSS code: input: focus, textarea: focus {border:; background :;}

Problem: IE6 does not support hover pseudo-class selectors except hyperlink Elements

Solution:

1. Add a style named focus to css.

.focus{       border:;       background:;}

2. Add get and lose focus events to the text box

$(function(){        $(":input").focus(function(){                 $(this).addClass("focus");}).blur(function(){                  $(this).removeClass("focus");        });});

 

2. Multi-line text box

(1) height change

$ Comment. height ($ comment. height () + 50); equivalent to $ comment. animate ({height: "+ = 50"}, 400 );

$ (Function () {var $ comment =$ ('# comment'); $ ('. bigger '). click (function () {if (! $ Comment. is (": animated") {// determines whether the animation is in if ($ comment. height () <500) {$ comment. animate ({height: "+ = 50"}, 400) ;}}) $ ('. smaller '). click (function () {if (! $ Comment. is (": animated") {// determines whether the animation is in if ($ comment. height () <500) {$ comment. animate ({height: "-= 50"}, 400 );}}})});

(2) the height of the scroll bar changes.

By controlling the change of the scroll bar of the multi-line text box, you can scroll the content in the text box. Here you only need to control the attribute scrollTop.

 

3. Check box

Select All, reselect, and deselect check boxes.

(1) select all or not -- you can control the checked attribute of an element. If the value of the property checked is true, it indicates that it is selected. If the value is false, it indicates that it is not selected.

Select All:

$("#CheckedAll").click(function(){      $('[name=items]:checkbox').attr('checked',true);});

Not all:

$("#CheckedAll").click(function(){      $('[name=items]:checkbox').attr('checked',false);});

(2) Select inverse -- cycle each check box to set them to be worth the inverse value. That is, if it is true, set it to false. If it is false, set it to true, you can use the non-operator "!".

$("#CheckedRev").click(function(){      $('[name=items]:checkbox').each(function(){           $(this).attr('checked',!$(this).attr("checked"));      });});

Checked =! $ (This). attr ("checked ")

Simplified code:

$("#CheckedRev").click(function(){      $('[name=items]:checkbox').each(function(){           this.checked=!this.checked;      });});

(3) Submit: after the check box is selected, the user clicks the "Submit" button to output the value of the selected item. You can use the val () method or the selected value.

$ ("# Send "). click (function () {var str = "you selected: \ r \ n"; $ ('[name = items]: checkbox: checked '). each (function () {str + = $ (this ). val () + "\ r \ n" ;}); alert (str );});

(4) use the check box to control whether to select all or not

First, control the other check box

$("#CheckedAll").click(function(){         if(this.checked){               $('[name=items]:checkbox').attr('checked',true);      }else{               $('[name=items]:checkbox').attr('checked',false);      }});  

Because the value of the checked attribute of the check box is the same as that of the checked attribute of the check box that is fully selected, if judgment can be omitted.

$("#CheckedAll").click(function(){      $('[name=items]:checkbox').attr('checked',this.checked);});

Associate the all-selected box with the check box group by performing the following steps:

① Bind a click event to the check box Group

② Define a flag variable. The default value is true.

③ Check box group. When there are unselected options, the flag value of the variable is set to false.

④ Set the check box id to "CheckedAll" based on the flag value of the variable to check whether it is selected

$('[name=items]:checkbox').click(function(){      var flag=true;      $('[name=items]:checkbox').each(function(){              if(!this.checked){                         flag=false;              }      });      $('#CheckedAll').attr('checked',flag);});  

Method 2:

① Bind a click event to the check box Group

② Determine whether the total number of check box groups is equal to the number of check boxes selected

③ If they are equal, select all. Otherwise, no.

 

4. drop-down list

Click the button in the middle to add the selected options on the left to the right. You can also add the options on the right to the left, or double-click the options to add them to the other side.

HTML code:

<div>         <select multiple  id="select1">$('#add').click(function(){        var options=$('#select1 option:selected');        var $remove=$option.remove();        $remove.appendTo('#select1');});

You can use the appendTo () method to delete and append the two steps, which can be simplified:

$('#add').click(function(){        var options=$('#select1 option:selected');        $options.appendTo('#select2');});  

Second function: add all options to the other party

$('#add_all').click(function(){        var options=$('#select1 option');        $options.appendTo('#select2');});   

Third function: Double-click an option to add it to the peer.

① Bind a double-click event to the drop-down list; ② get the selected option through $ ("option: selected", this)

$('#select1').dblclick(){      var  $options=$("option:selected",this);      $options.appendTo('#select2');}

 

5. Form Verification

Html section:

<Form method = "post" action = "">
<Div class = "int"> <label for = "username"> User name: </label> <! -- Add required for each required element --> <input type = "text" id = "username"Class = "required"/> </Div> <div class =" int "> <label for =" email "> email: </label> <input type = "text" id = "email" class = "required"/> </div> <div class = "int"> <label for =" personinfo "> personal data: </label> <input type = "text" id = "personinfo"/> </div> <div class = "sub"> <input type = "submit" value =" submit "id =" send "/> <input type =" reset "id =" res "/> </div>
</Form>

Analysis:

(1) The text box with the class Attribute "required" in the form must be filled in. Therefore, it must be different from other non-mandatory form elements, that is: append a red star icon to the text box.

$ ("Form: input. required "). each (function () {var $ required = $ ("<strong class = 'high'> * </strong>"); // create an element $ (this ). parent (). append ($ required); // then append it to the document });

(2) When the user fills in the information in the "user name" text box and removes the cursor focus from the "user name", it is necessary to determine whether the user name meets the authentication rules. The same is true for the mailbox, therefore, to add a focus loss event to the form element, follow these steps:

① Determine whether the element that loses focus is "User Name" or "Mailbox", and process them separately

② If it is a user name, judge whether the length of the element value is less than 6. If it is less than 6, use red to remind the user that the input is incorrect. Otherwise, use green to remind the user that the input is correct.

③ If it is a mailbox, judge whether the element value conforms to the mailbox format. If it does not match, use red to remind the user that the input is incorrect. Otherwise, use green to remind the user that the input is correct.

④ Append the reminder information to the end of the parent element of the current element

 

JQuery Verification Section:

<Script type = "text/javascript"> // <! [CDATA [$ (function () {/** the idea is to first add a required tag for each required and implement it using the each () method. * Create an element in the each () method. Then, add the created element to the parent element through the append () method. * This describes the essence of this. Each time this corresponds to the corresponding input element, the corresponding parent element is obtained. * Then add a focus loss event to the input element. Then, verify the user name and email. * Here we use a judgment is (). If it is a user name, it will be processed accordingly. If it is an email, it will be verified accordingly. * In the jQuery framework, you can also insert original javascript code. For example, the authentication username contains this. value, and this. value. length. Determine the content. * Then, the email is verified. It seems that a regular expression is used. * Add a keyup event and a focus event to the input element. The verification is also required during keyup. You can call the blur event. TriggerHandler () trigger is used to trigger the corresponding event. * Perform unified verification when submitting the form at the end * handle the whole and details * // if required, add the Red Star logo. $ ("form: input. required "). each (function () {var $ required = $ ("<strong class = 'high'> * </strong>"); // create an element $ (this ). parent (). append ($ required); // then append it to the document}); // after the text box loses focus, a new reminder element will be created each time the element loses focus, append it to the document, and the prompt message appears multiple times. Before creating a reminder element, delete the reminder element before the current element.

$ ('Form: input'). blur (function (){

Var $ parent = $ (this). parent ();

$ Parent. find (". formtips "). remove (); // verify the username if ($ (this ). is ('# username') {if (this. value = "" | this. value. length <6) {var errorMsg = 'enter at least 6 usernames. '; $ parent. append ('<span class = "formtips onError">' + errorMsg + '</span>');} else {var okMsg = 'the input is correct. '; $ parent. append ('<span class = "formtips onSuccess">' + okMsg + '</span>') ;}// verify the email if ($ (this ). is ('# email') {if (this. value = "" | (this. value! = ""&&! /. + @. + \. [A-zA-Z] {2, 4} $ /. test (this. value) {var errorMsg = 'enter the correct email address. '; $ parent. append ('<span class = "formtips onError">' + errorMsg + '</span>');} else {var okMsg = 'the input is correct. '; $ parent. append ('<span class = "formtips onSuccess">' + okMsg + '</span> ');}}
// Bind the keyup event and focus event to the form element. The keyup event can be triggered every time you release the button to implement instant notification, instead of reminding the input to be correct after the field element loses focus each time, the focus event can be triggered when the element gets focus to implement instant reminders. }). Keyup (function () {$ (this ). triggerHandler ("blur ");}). focus (function () {$ (this ). triggerHandler ("blur") ;}); // end blur // submit, final verification, trigger () method to trigger the blur event. The length of the class "onError" element is used to determine whether the object can be submitted. If the length is 0, the request can be submitted. Otherwise, the request is false, indicating that an error exists. You must prevent the form from being submitted, to prevent form submission, you can directly use the "return false" Statement $ ('# send '). click (function () {$ ("form: input. required "). trigger ('blur'); var numError = $ ('form. onerror '). length; if (numError) {return false;} alert ("registration successful, the password has been sent to your mailbox, please check. ") ;}); // reset $ ('# res '). click (function () {$ (". formtips "). remove () ;};}) //]> </script>

Note: trigger ("blur") triggers not only the blur event bound to the element, but also the default blur event of the browser, that is, the cursor cannot be positioned on the text box. TriggerHandler ("blur") only triggers the blur event bound to the element, rather than the default blur event of the browser.

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.