Automatic match of input box (native code) _ javascript skills

Source: Internet
Author: User
Functional requirements: implemented using native code. No framework can be used to match only English characters, in addition, the matched content can be bold in the menu, and the menu can be selected through the up and down arrows on the keyboard, if you are interested, you can refer to the following questions that people in the group have initiated before Renren. I have reposted some questions before. I am just idle and choose one question to do it.

This question has the following requirements::
1. Use native code for implementation, and do not use any framework;
2. Match the characters entered in the input box and display the matched content in the menu below the input box;
3. Only English characters are matched, and the matched content is bold in the menu;
4. You can select a menu by using the up and down arrows on the keyboard. Press enter to write the selected content to the input box;
Si Lu
Capture input changes. Use the value entered by the user (hereinafter referred to as the input value) to match the list items. Here we assume that the list items are an array returned by the query (hereinafter referred to as the list ), the matching method is to use the input value as the starting value to match each list value, and output the items that meet the filtering conditions to the page.
Analysis
In the third requirement, the keyword is bold. Here we can replace it with a regular expression.
The fourth point requires a lot of keywords. In a single sentence, there are a lot of passwords hidden. This part is mainly for the keyboard. First, the upper and lower buttons, then the carriage return, and a write to the input box.

At this point, if you think it is over, you will be in a hurry. There are at least four implicit requirements.
• The first item is highlighted by default, and the current item is highlighted when both the upper and lower buttons are pressed.
• Press Enter. The first item is selected by default.
• Highlight the current item when the mouse passes.
• Click the selected item.
There may be some omissions, so I won't be confused here.
Practice
This is a JS question, but before that, the page structure should be written first.

The Code is as follows:








  • Placeholder

  • Zhankeng





Because the framework is not allowed, some possible methods are encapsulated here.
First, create an encapsulated object and name it dom for the time being. Then the native method will put this object for reuse.

The Code is as follows:


Var dom = {
$: Function (id ){
Return document. getElementById (id );
},
Tag: function (tagName, root ){
Root = root? Root: document;
Return this. makeArray (root. getElementsByTagName (tagName ));
},
Bind: function (element, type, handler ){
If (document. addEventListener ){
Element. addEventListener (type, handler, false );
} Else if (document. attachEvent ){
Element. attachEvent ('on' + type, handler );
};
},
RemoveClass: function (list, name ){
Var el = list [I],
R = new RegExp ('\ s * \ B' + name + '\ B \ s *', 'G ');
For (var I = 0, len = list. length; I <len; I ++ ){
Var cur = list [I];
If (r. test (cur. className )){
Cur. className = cur. className. replace (r ,'');
};
};
},
Height: function (element ){
Return element. offsetHeight;
},
GetBound: function (element ){
Return element. getBoundingClientRect ();
},
GetText: function (element ){
Return element. textContent? Element. textContent: element. innerText;
},
Trim: function (string ){
Return string. replace (/^ \ s * (. *) \ s * $/, '$1 ');
},
MakeArray: function (tagList ){
For (var I = 0, arr = [], len = tagList. length; I <len; I ++ ){
Arr. push (tagList [I]);
};
Return arr;
},
IsVisible: function (element ){
Return element. style. display = 'block ';
}
};


Then create an object to store the specific processing logic. The author compares the English language with the dog blood, so it is called automatic.
This object has to do more:
• Determine the menu position;
• Real-time processing of user input;
• Handling mouse and keyboard buttons;
To determine the menu position, use the getBound method of the encapsulated object dom to return a boundary object, which has two properties: left and top. Familiar with it. It is similar to the offset () method in jQuery.
Processing user input is worth mentioning here. Because it is real-time processing, it is unreasonable to consider using the onchange event, but it will only be triggered when the focus is lost.
At this time, I turned to oninput, which is fully competent for the job.

The Code is as follows:


Dom. bind (obj. input, 'input', this. inputProcess );


However, Internet Explorer has done something unusual. It does not support oninput.
I'm so happy!
There is always a turning point in everything. Onpropertychange in the corner is coming slowly ..., It is very similar to oninput and has the same features. At least in terms of capturing input, it is exactly what I want. To deal with IE, we all use it.
Bind again:

The Code is as follows:


Dom. bind (obj. input, 'propertychang', this. inputProcess );


Next, press the button, top, bottom, and press Enter. The corresponding key codes are 38, 40, and 13 respectively. Note that the attribute names of FF and IE are different.
For detailed implementation details, see the Demo:
Slam me to view the Demo
In real business scenarios, real-time Ajax queries may be performed on user input, which means that a query is performed every time a letter is typed.
However, it is really not cost-effective to send Ajax requests so frequently, and such implementation is not allowed in response speed.
My idea is to send a request when the user knocks on the first letter (the number of request data is generally limited, usually 10) and store the return value (hereinafter referred to as cache ).
User input after the first letter is filtered in the cache. Here it is like a local query. Each input letter has a higher accuracy and a smaller cache.
Repeat the preceding steps when the user clears and re-enters the data.
Of course, it is not ruled out that there will be some more complex business scenarios. For example, when there is sufficient matching, make sure that each user input has 10 data records (optional, this requires more judgment and requests.
Therefore, the specific implementation depends on the real business scenario.
This article ends. Thank you for reading. You are welcome to comment.

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.