Input input box automatic matching (native code) _javascript tips

Source: Internet
Author: User
Tags tagname
Today, see some people in the group launched a network of all the previous interview questions, I have reproduced some before, just idle, pick a topic to do, practice a hand.

here are the following requirements
1. Use of native code to achieve, do not use any framework;
2. The characters entered in the input box to match, will be matched to the contents of the menu displayed in the form below the input box;
3. Matches only for English characters, and the matching content is bold in the menu;
4. Through the keyboard on the up and down arrows can select the menu, press ENTER after the selected content to write to the input box;
train of Thought
To capture input changes, use the value entered by the user (the input value below) to match the list item, where it is assumed that the list item is an array returned by the query (the next list), and the matching method will be output to the page with the input value as the start value matching each list value.
Analysis
The 3rd requirement in the keyword is bold, here with a regular replacement is good.
The 4th requirement of the keyword is more, a word hidden many murderous, this part is mainly for the keyboard, the first is up and down the key, then enter, there is a write to the input box.

Here, if you think it's over, it's too late. There are at least 4 hidden needs.
• The first item is highlighted by default, and the current item is highlighted while the button is up and down.
• Press Enter the default first item is selected.
• The current item is highlighted when the mouse passes.
• Support click on selected items.
There may be some omission, there is no tangle.
Practice
Although this is a JS problem, but before this, the page structure must first write well.
Copy Code code as follows:

<div id= "Wrap" >
<input type= "text" id= "put"/>
</div>
<div id= "Menu" >
<div>
<ul id= "Output" >
<li> placeholder </li>
<li> occupy the Pit </li>
</ul>
</div>
</div>

Because frames are not allowed, there is a simple encapsulation of some possible methods.
First create a wrapper object, then name the DOM, and the next native method is put into this object for reuse.
Copy Code code 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*$/, ' $ ');
},
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 of the English comparison of dog blood, called Automatch Bar.
There are many things to do with this object:
• Determine the location of the good menu;
• Real-time processing of user input;
• Handle mouse and keyboard key actions;
To determine the location of the menu, use the Getbound method of encapsulating the object Dom to return a boundary object that has two properties left and top. Looks familiar, it resembles the offset () method in jquery.
Processing user input It is worth mentioning that, because it is real-time processing, start to consider using the onchange event, but it will only be triggered when the focus is lost, so it is unreasonable.
Then my eyes turned to oninput, and it was perfectly capable of working.
Copy Code code as follows:

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

However, IE has done a return to do not take the usual road thing. It does not support oninput.
Empty happy one, white blind!
There is always a turnaround in everything. The corner of the onpropertychange to us slowly ..., it and oninput very similar, have the same characteristics, at least in the capture input, it is what I want, against IE, we all use it, with all said.
To bind once again:
Copy Code code as follows:

Dom.bind (obj.input, ' PropertyChange ', this.inputprocess);

Next is the button, up, down, enter. The corresponding key encoding is 38, 40, 13, the only thing to note is that FF and IE have different property names.
Detailed implementation details see demo:
Bash me in to see the demo
In a real-world business scenario, you might want to make real-time Ajax queries about the user's input, which means that every time you hit a letter, you will have a query.
However, it is not cost-effective to send AJAX requests so frequently, nor does the response speed allow such implementations.
My idea is that when the user knocks on the first letter, send a request (the request data is typically limited in number, typically 10), and the return value is stored (hereinafter called the cache).
The user input after the first letter is filtered in the cache, and here is the same as the local query, with every letter entered, the precision is getting higher and the cache is getting smaller.
Repeat the steps above when the user empties and reenter.
Of course, there will be some more complex business scenarios, for example, in the case of sufficient matching, to ensure that the user input every time 10 data is optional, which requires more judgment and request.
So, the actual implementation depends on the real business scenario.
This concludes the article. Thank you for reading and welcome to comment with flesh and blood.

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.