Javascript input box email auto-Prompt function code implementation _ javascript tips-js tutorial

Source: Internet
Author: User
When I enter any words in an input box, the corresponding email box will be automatically pulled down and prompted. When I enter 11 in the input box, all 11 mailboxes in the drop-down box will have the corresponding email box for other texts, the following automatic prompt function is implemented. Similarly, this plug-in does not require any html tags. It only requires a corresponding class name in the input box and the parent class name, none of them are required. Internal HTML code is automatically generated.

The HTML code is as follows:

The Code is as follows:





In fact, the above p labels do not need to be added in the input box and the parent element to the above class (User-Defined can also, only when JS Initialization is required, it is OK to pass in the class. By default, the parent class is parentCls. The class in the current input box is inputElem, and the class in the hidden field is hiddenCls, you can directly initialize the input null object during initialization !). Because there may be multiple input boxes on the page, a parent class is required to distinguish the input box. Of course, a hidden Domain value should be provided to the development background.

The configuration item contains a mailbox array parameter mailArr: ["@ qq.com", "@ qq2.com", "@ gmail.com", "@ 126.com"," @ 163.com", "@ hotmail.com ", "@ yahoo.com", "@ yahoo.com.cn", "@ live.com", "@ sohu.com", "@ sina.com"]. It is to tell us that there are so many default mailboxes, No matter what drop-down box I enter, there are so many mailbox prompts during initialization, when I get a certain item, I will give a prompt to get a specific item. Of course, because you need to change the mailbox parameter, you can configure it as needed during initialization.

The Code style is the same as before.

The following functions are implemented:

1. You can move the keyboard down or press Enter.

2. When you click document, the drop-down box is hidden except the current input box. When the input is followed, automatic matching is implemented.

Not to mention, it is similar to the automatic mailbox prompt function during online registration. If you have any bugs, you can leave a message for me. It's not too late! Directly paste the Code:

The CSS code is as follows:

The Code is as follows:



The JS Code is as follows:

The Code is as follows:


/**
* Email auto-Prompt plug-in
* @ Constructor EmailAutoComplete
* @ Options {object} configurable items
*/

Function EmailAutoComplete (options ){

This. config = {
TargetCls: '. inputElem', // target input element
ParentCls: '. parentcls', // The parent class of the current input element
HiddenCls: '. hiddencls', // hide the current input field
SearchForm: '. jqtransformdone', // form
HoverBg: 'hoverbg ', // background for moving the cursor up
InputValColor: 'red', // enter the color of the prompt in the input box.
MailArr: ["@ qq.com", "@ qq2.com", "@ gmail.com", "@ 126.com"," @ 163.com", "@ hotmail.com", "@ yahoo.com ", "@ yahoo.com.cn", "@ live.com", "@ sohu.com", "@ sina.com"], // email Array
IsSelectHide: true, // click whether to hide the drop-down box. The default value is true.
Callback: null // click a callback function
};
This. cache = {
OnlyFlag: true, // rendering only once
CurrentIndex:-1,
OldIndex:-1
};

This. init (options );
}

EmailAutoComplete. prototype = {

Constructor: EmailAutoComplete,

Init: function (options ){
This. config = $. extend (this. config, options || {});

Var self = this,
_ Config = self. config,
_ Cache = self. cache;

Detail (_config.tar getCls). each (function (index, item ){

$ (Item). keyup (function (e ){
Var target = e.tar get,
TargetVal = $. trim ($ (this). val ()),
Keycode = e. keyCode,
ElemHeight = $ (this). outerHeight (),
ElemWidth = $ (this). outerWidth (),
ParentNode = $ (this). closest (_ config. parentCls );

Vertex (parentnode).css ({'position': 'relative '});
// Hide the drop-down box if the input box value is null
If (targetVal = ''){
$ (Item). attr ({'data-html ':''});
// Assign values to hidden fields
$ (_ Config. hiddenCls, parentNode). val ('');

_ Cache. currentIndex =-1;
_ Cache. oldIndex =-1;
$ (". Auto-tip", parentNode )&&! $ (". Auto-tip", parentNode). hasClass ('den den ') & $ (". auto-tip", parentNode). addClass ('den den ');
Self. _ removeBg (parentNode );
} Else {

$ (Item). attr ({'data-html ': targetVal });

// Assign values to hidden fields
$ (_ Config. hiddenCls, parentNode). val (targetVal );

$ (". Auto-tip ", parentNode) & $ (". auto-tip ", parentNode ). hasClass ('hiddy') & $ (". auto-tip ", parentNode ). removeClass ('ddn ');
// Render the content of the drop-down box
Self. _ renderHTML ({keycode: keycode, e: e, target: target, targetVal: targetVal, height: elemHeight, width: elemWidth, parentNode: parentNode });
}


});
});

// Prevent form from submitting by default the enter key
$ (_ Config. searchForm). each (function (index, item ){
$ (Item). keydown (function (e ){
Var keyCode = e. keyCode;
If (keyCode = 13 ){
Return false;
}
});
});

// Hide the drop-down list when you click document
$ (Document). click (function (e ){
E. stopPropagation ();
Var target = e.tar get,
TagCls = _config.tar getCls. replace (/^ \./,'');

If (! $ (Target). hasClass (tagCls )){
$ ('. Auto-tip') & $ ('. auto-tip'). each (function (index, item ){
! $ (Item). hasClass ('den den ') & $ (item). addClass ('den den ');
});
}
});
},
/*
* Rendering drop-down box prompt content
* @ Param cfg {object}
*/
_ RenderHTML: function (cfg ){
Var self = this,
_ Config = self. config,
_ Cache = self. cache,
CurVal;
Var curIndex = self. _ keyCode (cfg. keycode );

$ ('. Auto-tip ', cfg. parentNode ). hasClass ('hiddy') & $ ('. auto-tip ', cfg. parentNode ). removeClass ('ddn ');
If (curIndex>-1 ){
// Upper and lower operations on the keyboard
Self._keyUpAndDown(cfg.tar getVal, cfg. e, cfg. parentNode );
} Else {
If (// @/.test(cfg.tar getVal )){
CurVal = cfg.tar getVal. replace (/@.*/,'');
} Else {
CurVal = cfg.tar getVal;
}
If (_ cache. onlyFlag ){
$ (Cfg. parentNode). append ('');
Var wrap ='

    ';

    For (var I = 0; I <_ config. mailArr. length; I ++ ){

    Wrap + ='

  • '+''+ _ Config. mailArr [I] +'
  • ';
    }
    Wrap + ='
';
_ Cache. onlyFlag = false;
$ (Cfg. parentNode). append (wrap );
Parameters ('.auto-tip', cfg.parentnode).css ({'position': 'absolute ', 'top': cfg. height, 'width': cfg. width-2 + 'pxy', 'left': 0,
'Border': '1px solid # ccc ', 'z-Index': 10000 });
}

// Add the data-html attribute to all li
$ ('. Auto-tip li', cfg. parentNode). each (function (index, item ){
Parameters ('.output-num', item0000.html (curVal );
! $ ('. Output-num', item). hasClass (_ config. inputValColor )&&
$ ('. Output-num', item). addClass (_ config. inputValColor );
Var emVal = $. trim ($ ('. em', item). attr ('data-html '));
$ (Item). attr ({'data-html ': curVal + ''+ emVal });
});

// Exact match content
Self. _ accurateMate ({target: cfg.tar get, parentNode: cfg. parentNode });

// Move the cursor over a li item
Self. _ itemHover (cfg. parentNode );

// When you click the corresponding item
Self. _ executeClick (cfg. parentNode );
}

},
/**
* Exact match of a specific item
*/
_ AccurateMate: function (cfg ){
Var self = this,
_ Config = self. config,
_ Cache = self. cache;

Var curVal = pai.trim((cfg.tar get, cfg. parentNode). attr ('data-html ')),
NewArrs = [];
If (// @/. test (curVal )){

// Obtain the value following @
Var prefix = curVal. replace (/@.*/,""),
Suffix = curVal. replace (/.*@/,"");

$. Map (_ config. mailArr, function (n ){
Var reg = new RegExp (suffix );
If (reg. test (n )){
NewArrs. push (n );
}
});
If (newArrs. length> 0 ){
('.Auto-tip', cfg.parentnode.html .html ('');
$ (". Auto-tip", cfg. parentNode) & $ (". auto-tip", cfg. parentNode). hasClass ('den den ')&&
$ (". Auto-tip", cfg. parentNode). removeClass ('den den ');

Var html = '';
For (var j = 0, jlen = newArrs. length; j <jlen; j ++ ){
Html + ='

  • '+''+ NewArrs [j] +'
  • ';
    }
    Certificate ('.auto-tip', cfg.parentnode).html (html );

    // Add the data-html attribute to all li
    $ ('. Auto-tip li', cfg. parentNode). each (function (index, item ){
    Parameters ('.output-num', item#.html (prefix );
    ! $ ('. Output-num', item). hasClass (_ config. inputValColor )&&
    $ ('. Output-num', item). addClass (_ config. inputValColor );

    Var emVal = $. trim ($ ('. em', item). attr ('data-html '));

    $ (Item). attr ('data-html ','');
    $ (Item). attr ({'data-html ': prefix + ''+ emVal });
    });

    // Exact match to make the current index equal to the initial value
    _ Cache. currentIndex =-1;
    _ Cache. oldIndex =-1;

    $ ('. Auto-tip .output-num', cfg.parentnode).html (prefix );

    // Move the cursor over a li item
    Self. _ itemHover (cfg. parentNode );

    // When you click the corresponding item
    Self. _ executeClick (cfg. parentNode );
    } Else {
    $ (". Auto-tip", cfg. parentNode )&&! $ (". Auto-tip", cfg. parentNode). hasClass ('den den ')&&
    $ (". Auto-tip", cfg. parentNode). addClass ('den den ');
    ('.Auto-tip', cfg.parentnode.html .html ('');
    }
    }
    },
    /*
    * When you move the cursor over a li item
    */
    _ ItemHover: function (parentNode ){
    Var self = this,
    _ Config = self. config,
    _ Cache = self. cache;
    $ ('. Auto-tip li', parentNode). hover (function (index, item ){
    ! $ (This). hasClass (_ config. hoverBg) & $ (this). addClass (_ config. hoverBg );
    }, Function (){
    $ (This). hasClass (_ config. hoverBg) & $ (this). removeClass (_ config. hoverBg );
    });
    },
    /*
    * When the input box value is null, class hoverBg is deleted for all li items.
    */
    _ RemoveBg: function (parentNode ){
    Var self = this,
    _ Config = self. config;

    $ (". Auto-tip li", parentNode). each (function (index, item ){
    $ (Item). hasClass (_ config. hoverBg) & $ (item). removeClass (_ config. hoverBg );
    });
    },
    /**
    * Keyboard up/down key operations
    */
    _ KeyUpAndDown: function (targetVal, e, parentNode ){
    Var self = this,
    _ Cache = self. cache,
    _ Config = self. config;

    // If data is returned after the request is successful (determined based on the length of the element), perform the following operations:
    If ($ ('. auto-tip' + 'lil', parentNode) & $ ('. auto-tip' + 'lil'). length> 0 ){

    Var plen = $ ('. auto-tip' + 'lil', parentNode). length,
    KeyCode = e. keyCode;
    _ Cache. oldIndex = _ cache. currentIndex;

    // Move up
    If (keyCode = 38 ){
    If (_ cache. currentIndex =-1 ){
    _ Cache. currentIndex = plen-1;
    } Else {
    _ Cache. currentIndex = _ cache. currentIndex-1;
    If (_ cache. currentIndex <0 ){
    _ Cache. currentIndex = plen-1;
    }
    }
    If (_ cache. currentIndex! =-1 ){

    ! $ ('. Auto-tip. p-Index' + _ cache. currentIndex, parentNode). hasClass (_ config. hoverBg )&&
    $ ('. Auto-tip. p-Index' + _ cache. currentIndex, parentNode ). addClass (_ config. hoverBg ). siblings (). removeClass (_ config. hoverBg );

    Var curAttr = $ ('. auto-tip' + '. p-Index' + _ cache. currentIndex, parentNode). attr ('data-html ');
    Vertex (_config.tar getCls, parentNode). val (curAttr );

    // Assign values to hidden fields
    $ (_ Config. hiddenCls, parentNode). val (curAttr );
    }

    } Else if (keyCode = 40) {// move down
    If (_ cache. currentIndex = plen-1 ){
    _ Cache. currentIndex = 0;
    } Else {
    _ Cache. currentIndex ++;
    If (_ cache. currentIndex> plen-1 ){
    _ Cache. currentIndex = 0;
    }
    }

    If (_ cache. currentIndex! =-1 ){

    ! $ ('. Auto-tip. p-Index' + _ cache. currentIndex, parentNode). hasClass (_ config. hoverBg )&&
    $ ('. Auto-tip. p-Index' + _ cache. currentIndex, parentNode ). addClass (_ config. hoverBg ). siblings (). removeClass (_ config. hoverBg );

    Var curAttr = $ ('. auto-tip' + '. p-Index' + _ cache. currentIndex, parentNode). attr ('data-html ');
    Vertex (_config.tar getCls, parentNode). val (curAttr );
    // Assign values to hidden fields
    $ (_ Config. hiddenCls, parentNode). val (curAttr );
    }

    } Else if (keyCode = 13) {// press ENTER
    Var curVal = $ ('. auto-tip' + '. p-Index' + _ cache. oldIndex, parentNode). attr ('data-html ');
    Vertex (_config.tar getCls, parentNode). val (curVal );

    // Assign values to hidden fields
    $ (_ Config. hiddenCls, parentNode). val (curVal );

    If (_ config. isSelectHide ){
    ! $ (". Auto-tip", parentNode). hasClass ('den den ') & $ (". auto-tip", parentNode). addClass ('den den ');
    }
    _ Config. callback & $. isFunction (_ config. callback) & _ config. callback ();

    _ Cache. currentIndex =-1;
    _ Cache. oldIndex =-1;

    }
    }
    },
    _ KeyCode: function (code ){
    Var arrs = ['17', '18', '38', '40', '37', '39', '33', '34', '35 ', '46', '36', '13', '45', '44', '123', '19', '20', '9'];
    For (var I = 0, ilen = arrs. length; I <ilen; I ++ ){
    If (code = arrs [I]) {
    Return I;
    }
    }
    Return-1;
    },
    /**
    * If the data is the same, click the corresponding item to return the data.
    */
    _ ExecuteClick: function (parentNode ){

    Var _ self = this,
    _ Config = _ self. config;

    $ ('. Auto-tip' + 'lil', parentNode). unbind ('click ');
    $ ('. Auto-tip' + 'lil', parentNode). bind ('click', function (e ){
    Var dataAttr = $ (this). attr ('data-html ');

    Vertex (_config.tar getCls, parentNode). val (dataAttr );
    If (_ config. isSelectHide ){
    ! $ (". Auto-tip", parentNode). hasClass ('den den ') & $ (". auto-tip", parentNode). addClass ('den den ');
    }
    // Assign values to hidden fields
    $ (_ Config. hiddenCls, parentNode). val (dataAttr );
    _ Config. callback & $. isFunction (_ config. callback) & _ config. callback ();

    });
    }
    };

    // Initialization
    $ (Function (){
    New EmailAutoComplete ({});
    });

    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.