jquery Input Box Plugin

Source: Internet
Author: User

Objective

In the development of large-scale projects, plug-in is a trend, the similar multi-use of things packaged into a public plug-in, to improve development efficiency. Other developers can implement very complex content or effects with a simple one or two-line code when invoking a Plugin.

In this section I will share with you how I encapsulate an input box plugin.

"rendering analysis"

(1) default Display: The border is gray, the middle has the input prompt information

(2) get focus: The border is blue, there is no input in the middle of the input message, the input content when the middle display input

(3) lose focus: Enter the correct border into a light green, and a √; input error, red border, and an X

"functional analysis"

Private Method: No external embodiment, plug-in internal calls;

Public methods: externally provided interfaces that other developers can invoke

(1) draw the DOM (private method): based on the HTML structure inside the rendering analysis, use jquery to draw it dynamically.

(2) Focus Event (private method): an event such as moving an input box binding into a move out, and a different status input box should be rendered differently.

(3) legality test (private method): according to the input content, verify the legitimacy of the input, and give a hint.

(4) length Check (private method): Verify the length of the input according to the input, and give a hint.

(5) State Presentation (private method): show different states based on the results of the checksum (correct, error, lose focus, get Focus)

(6) set Size (public method): Other developers can change the size of the input box as needed by this method

(7) Gray function (public method): Sometimes we need to gray the input box, prohibit the user to change its value.

(8) Value acquisition (public method): input Box The most important of course is the value inside, This method must be provided to other developers to Call.

(9) value Reset (public method): Most of the time, we need to give the input box the initial value, such as when we first entered the page, so this method is also necessary.

(10) default value (public method): called when other developers need to customize the input box.

"development steps"

(1) draw a simple DOM

Before we encapsulate a component, we'd better write out its HTML structure so that it's good for quick layout when we encapsulate it. According to the above requirements its DOM structure is as Follows:

<Divclass= "input_container">    <inputtype= "text"class= "input_text input_text_blur"placeholder="">    <Divclass= "input_result"></Div></Div>

(2) Initialize plug-ins: store common values and invoke functions that draw the DOM structure of the input box

 //  Initialize plugin  init: function   () { //  common values Store  var  _this = this  ;    _this.type  = _this.settings.type;    _this.spec  = _this.settings.spec;    _this.length  = _this.settings.length;    _this.placeholder  = _this.settings.placeholder;    _this.isrequired  = _this.settings.isrequired;  //  Initialize the input box DOM structure   _this._initinputdom ();},  

(3) Initialize the input box Dom structure: using jquery to dynamically generate the DOM structure, to avoid other developers to manually write, in fact, using jquery will be the first step of the three HTML interface written out, write a lot, in fact, the function of one (*^__^*) ...

_initinputdom:function() {    var_this = this, Inputcontainer= $ (' <div></div> '), inputcontent= $ (' <input type= "' + _this.type + '" > '), Inputresult= $ (' <div></div> '); Inputcontainer.addclass (' Input_container '); Inputcontent.addclass (' Input_text Input_text_blur '); Inputresult.addclass (' Input_result ');    Inputcontainer.append (inputcontent);    Inputcontainer.append (inputresult);    _this.element.append (inputcontainer); //log the DOM that currently needs to be manipulated_this.input = _this.element.find (' input '); _this.container= _this.element.find ('. Input_container ')); if(_this.placeholder!==NULL) {        //Placeholder Tip information_this.input.prop (' placeholder ', _this.placeholder); } _this._initevent ();},

(4) bind event: Get focus, lose focus blur, Value change changes, need to be aware that when the input box is read-only, it is not necessary to bind the event

//Binding Events_initevent:function() {    var_this = this; //get focus, lose focus blur, Change the value    //do not operate if the input box is read-only_this.input.focus (function() {        if(!$( this). attr (' readonly ') {_this._setstatus ( this, ' Focus '); }}). Blur (function() {        if(!$( this). attr (' readonly ')) {            if(_this.getvalue () = = = ") {                if(_this.isrequired) {//Required fields lose focus_this._setstatus ( this, ' ERROR '); } Else {                    //non-mandatory fields lose focus_this._setstatus ( this, ' Blur '); }            } Else {                //There is a case for direct value verification                if(_this._checkspec ()) {_this._setstatus ( this, ' right '); } Else{_this._setstatus ( this, ' ERROR '); }}}). KeyUp (function() {_this._checklenght (); });;},

(5) Value Correctness check: Verify the correctness of the input by reading the rules of the input box value

// Check input box input content function () {    varthis;     return _this.spec.test (_this.getvalue ());},

(6) length Check: Verify the correctness of the input length by reading the length rule of the input box value

//Check input box input length_checklenght:function() {    var_this = this, Inputlength=_this.length,//8-32 Scope of this formatCurrentlength =_this.getvalue (). length,//whether the length is within rangeLengthflag =true; if(/^\d+-\d+$/. Test (inputlength)) {        //Interval Range        varValuerange = Inputlength.split ('-')); //Current value length is less than set range        if(parseint (valuerange[0], ten) >Currentlength) {lengthflag=false; }        //Current value length is greater than set range, shielded input        if(currentlength > parseint (valuerange[1], 10) {_this.setvalue (_this.getvalue (). substring (0, parseint (valuerange[1], 10))); }    } Else if(/^\d+$/. Test (inputlength)) {        //Fixed length        //current length is not equal to set length        if(currentlength!== parseint (inputlength, 10) ) {lengthflag=false; }    }    //the length is not floating in the interval red    if(!Lengthflag) {_this._setstatus (_this.input,' Error '); } Else{_this._setstatus (_this.input,' Focus '); }},

(7) set the status of the input box: according to the results of the check, show the different states

//Set Input box status, correct, error, lose focus, get focus_setstatus:function(inputobj, Status) {$ (inputobj). removeclass (' Input_text_focus input_text_blur input_text_right input_text_error '); $ (inputobj). Siblings ('. input_result '). removeclass (' input_result_right input_result_error '); if(status = = = "right") {$ (inputobj). addclass (' Input_text_right '); $ (inputobj). Siblings ('. input_result '). addclass (' input_result_right '). text (' √ ')); } Else if(status = = = "error") {$ (inputobj). addclass (' Input_text_error ') $ (inputobj). siblings ('. input_result '). addclass (' input_result_error '). text (' x '); } Else if(status = = = "blur") {$ (inputobj). addclass (' Input_text_blur '); } Else if(status = = = "focus") {$ (inputobj). addclass (' Input_text_focus '); }},

(8) Set the input box Size: provides a simple interface to set the size of the input box small,big, or the number

//Set the input box sizeSetSize:function(size) {var_this = this; varScalesize = 1; if(size = = ' small ')) {scalesize= 0.8; } Else if(size = = ' big ') {scalesize= 1.2; } Else if(parseint (size, 10)!==NaN) {scalesize= parseint (size, 10)    }; _this.container.css (' Transform ', ' scale (' + scalesize + ') ');},

(9) Gray operation: No input is allowed

// Input Frame Gray function (flag) {    varthis;     if (flag) {        _this.input.prop (' readonly ', ');     Else {        _this.input.removeattr (' readonly ');}    },

(10) get value, Reset Value implementation

// Get input Box value function () {        returnthis. Input.val ();    },// set Input box value  function(str) {    this. Input.val (str);}

(11) Custom Input Frame interface

//Default Parameters$.fn. Createinput.defaultvalue = {    //input Box type: Text,passwordType: "text",    //Input Box RulesSpecNULL,    //lengthLengthNULL,    //describe input fieldsPlaceholderNULL,    //is requiredIsrequired:false};

"how to invoke"

// generate the input box $ ("#username"). Createinput ({    "text",    /^[0-9]\d*$/,    ' 5-8 ',    ' cannot be empty, can only enter a number, Length is 5-8 ',    true}); // calling public methods var myinput = $ ("#username"). Data (' createinput '); myinput.setvalue ("1245");

jquery input Box plug-in

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.