Home Web Front-end JS Tutorial Automatic matching of input input box (native code)_javascript skills

Automatic matching of input input box (native code)_javascript skills

May 16, 2016 pm 05:40 PM
input automatic matching Input box

Today, someone in the group posted some interview questions from Renren.com. I have reposted some of them before. I happened to be free, so I picked a question to do and practice my skills.

This question has the following requirements:
1. Use native code to implement, no framework can be used;
2. Match the characters entered in the input box, and it will match The content is displayed below the input box in the form of a menu;
3. Only English characters are matched, and the matched content is bolded in the menu;
4. The menu can be navigated through the up and down arrows on the keyboard Make a selection, press Enter and write the selected content into the input box;
Idea
Capture the input changes and use the value entered by the user (hereinafter referred to as the input value) to match the list Item, here it is assumed that the list item is an array (hereinafter referred to as the list) returned by the query. 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
The keywords in the third requirement are bold, just replace them with regular expressions here.
The fourth point requires more keywords. One sentence hides many murderous intentions. This part is mainly for the keyboard. First, press the up and down keys, then press Enter, and write to the input box.

At this point, if you think it’s over, it’s too hasty. There are at least 4 hidden needs.
•The first item is highlighted by default, and the current item is highlighted while pressing the up and down keys.
•Press Enter and the first item will be selected by default.
•The current item is highlighted when the mouse passes over it.
•Supports clicking on selected items.
Maybe there is something missing, so I won’t worry about it here.
Practice
Although this is a JS question, the page structure must be written first.

Copy code The code is as follows:





Since frames are not allowed, here is a simple encapsulation of some possible methods.
First create an encapsulation object, let’s name it dom, and then put all the native methods into this object for reuse.
Copy code 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’s English is pretty bad, so let’s call it autoMatch.
This object has a lot to do:
•Determine the location of the menu;
•Process user input in real time;
•Process mouse and keyboard keystrokes;
Determine the location of the menu Use the getBound method of the encapsulated object dom to return a boundary object. This object has two attributes left and top. It may look familiar, it is similar to the offset() method in jQuery.
Handling user input is worth mentioning here. Since it is real-time processing, I started to consider using the onchange event, but it will only be triggered when the focus is lost, so it is unreasonable.
At this time, my eyes turned to oninput, which is fully capable of doing the job.
Copy code The code is as follows:

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

However, IE did something unconventional again. It does not support oninput.
The joy is all in vain!
There is always a turning point in everything. The onpropertychange in the corner is slowly coming towards us... It is very similar to oninput and has the same characteristics. At least in terms of capturing input input, it is exactly what I want. We all use it to deal with IE, and we all agree to use it. .
Bind again:
Copy code The code is as follows:

dom.bind( obj.input,'propertychange' , this.inputProcess );

The next step is the keys, up, down, and enter. The corresponding key codes are 38, 40, and 13 respectively. The only thing to note is that the attribute names of FF and IE are different.
See the Demo for detailed implementation details:
Click me to view the Demo
In a real business scenario, real-time Ajax query may be performed on the user's input, which means that every time a letter is typed There will be a query.
However, it is not cost-effective to send Ajax requests so frequently, and the response speed does not allow for such an implementation.
My idea is to send a request when the user types 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. It is like a local query. Every time a letter is entered, the accuracy becomes higher and higher, and the cache becomes smaller and smaller.
Repeat the above steps when the user clears and re-enters.
Of course, it is not ruled out that there will be some more complex business scenarios. For example, when there is sufficient matching, it is necessary to ensure that the user has 10 data options for each input, which requires more judgments and requests.
So, the specific implementation depends on the real business scenario.
This is the end of this article. Thanks for reading, and any flesh-and-blood comments are welcome.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to encapsulate input components and unified form data in vue3 How to encapsulate input components and unified form data in vue3 May 12, 2023 pm 03:58 PM

Preparation Use vuecreateexample to create a project. The parameters are roughly as follows: use native input. Native input is mainly value and change. The data needs to be synchronized when changing. App.tsx is as follows: import{ref}from'vue';exportdefault{setup(){//username is the data constusername=ref('Zhang San');//When the input box changes, synchronize the data constonInput=;return( )=>({

How to implement laravel input hidden field How to implement laravel input hidden field Dec 12, 2022 am 10:07 AM

How to implement the laravel input hidden field: 1. Find and open the Blade template file; 2. Use the method_field method in the Blade template to create a hidden field. The creation syntax is "{{ method_field('DELETE') }}".

What to do if there is no cursor when clicking on the input box What to do if there is no cursor when clicking on the input box Nov 24, 2023 am 09:44 AM

Solutions for clicking the input box without a cursor: 1. Confirm the focus of the input box; 2. Clear the browser cache; 3. Update the browser; 4. Use JavaScript; 5. Check the hardware device; 6. Check the input box properties; 7. Debug JavaScript code; 8. Check other elements of the page; 9. Consider browser compatibility.

Use jQuery to implement an input box that only allows numbers and decimal points to be entered Use jQuery to implement an input box that only allows numbers and decimal points to be entered Feb 26, 2024 am 11:21 AM

Implement jQuery input box to limit the input of numbers and decimal points. In web development, we often encounter the need to control what users input in the input box, such as restricting the input of numbers and decimal points only. This restriction can be achieved through JavaScript and jQuery. The following will introduce how to use jQuery to implement the function of limiting the input of numbers and decimal points in the input box. 1. HTML structure First, we need to create an input box in HTML, the code is as follows:

Detailed explanation of input box binding events in Vue documents Detailed explanation of input box binding events in Vue documents Jun 21, 2023 am 08:12 AM

Vue.js is a lightweight JavaScript framework that is easy to use, efficient and flexible. It is one of the most popular front-end frameworks currently. In Vue.js, input box binding events are a very common requirement. This article will introduce the input box binding events in the Vue document in detail. 1. Basic concepts In Vue.js, the input box binding event refers to binding the value of the input box to the data object of the Vue instance, thereby achieving two-way binding of input and response. In Vue.j

How to use the input box carriage return event and verification function in the Vue document How to use the input box carriage return event and verification function in the Vue document Jun 20, 2023 am 09:13 AM

Vue is a popular JavaScript front-end framework with a responsive data binding and component system at its core. In Vue applications, the input box is one of the most commonly used UI elements. When the user enters text, we hope to listen for the carriage return event and validate the input before submitting. This article will introduce the input box enter event and verification function usage in the Vue document. 1. The carriage return event of the input box in Vue. Monitoring the carriage return event of the input box in Vue is very simple.

What is the optimization method for input box length limit in Vue development? What is the optimization method for input box length limit in Vue development? Jun 30, 2023 am 08:44 AM

How to optimize the input box input length limit in Vue development Introduction: In the Vue development process, input box length limit is a common requirement. Limiting the number of characters users enter in the input box helps maintain data accuracy, optimize user experience, and improve system performance. This article will introduce how to optimize the input length limit of the input box in Vue development to provide a better user experience and development efficiency. 1. Use the v-model directive to bind the input box value. In Vue development, we usually use the v-model directive.

Teach you step by step how to use CSS to create a simple and elegant input box Teach you step by step how to use CSS to create a simple and elegant input box Jan 13, 2023 pm 03:55 PM

This article brings you relevant knowledge about CSS. It mainly introduces how to use CSS to implement a simple and sophisticated input box. I will teach you step by step~ Let’s take a look below. I hope it will be helpful to friends who need it. help.

See all articles