Home Web Front-end JS Tutorial How to implement the automatic completion input box function in JavaScript?

How to implement the automatic completion input box function in JavaScript?

Oct 20, 2023 pm 12:39 PM
- Function - Autocomplete - Input box Additional other

JavaScript 如何实现自动补全输入框功能?

How to implement the automatic completion input box function in JavaScript?

In web development, the auto-complete input box is a very common function. It can provide a fast, convenient and accurate input method and improve the user experience. This article will introduce how to use JavaScript to implement the auto-complete input box function and provide specific code examples.

1. HTML structure

First, we need to prepare an HTML structure containing an input box. An example is as follows:

<input type="text" id="autocomplete-input" placeholder="请输入关键字">
<ul id="autocomplete-list"></ul>
Copy after login

In the above example, we use the <input> element as the input box, set an id to "autocomplete-input", and add a placeholder attribute. In addition, we use a <ul> element as the auto-complete prompt list and set an id as "autocomplete-list".

2. JavaScript implementation

Next, we need to write JavaScript code to implement the automatic completion function. First, we need to listen to the input event of the input box and get the keywords entered by the user. We can then obtain the data related to the entered keyword through an Ajax request and display it in the auto-complete prompt list.

The following is a simple implementation example:

// 获取输入框和提示列表
var input = document.getElementById('autocomplete-input');
var list = document.getElementById('autocomplete-list');

// 监听输入框的输入事件
input.addEventListener('input', function() {
  var keyword = input.value;
  
  // 发送请求获取与关键字相关的数据
  // 这里可以根据实际情况进行后端接口的调用
  
  // 示例中使用一个静态的数据源来模拟请求
  var data = ['apple', 'banana', 'orange', 'grape', 'pineapple'];
  
  // 清空提示列表
  list.innerHTML = '';

  // 遍历数据,在提示列表中插入匹配的项
  for (var i = 0; i < data.length; i++) {
    if (data[i].indexOf(keyword) !== -1) {
      var item = document.createElement('li');
      item.textContent = data[i];
      list.appendChild(item);
    }
  }
});
Copy after login

In the above example, we first obtain the DOM elements of the input box and prompt list, and use the addEventListener method to listen for input The input event of the box. In the event handler function, we obtain the keyword entered by the user through the value attribute.

We can then send an Ajax request to obtain data related to the keyword. In the example, in order to simplify the code, we use a static data source to simulate the request. The specific implementation needs to call the backend interface according to the actual situation.

Next, we insert items matching the keyword into the prompt list by looping through the data array. By creating a <li> element, setting its text content using the textContent attribute, and finally adding it to the prompt list.

3. Style beautification

Finally, we can beautify the auto-complete prompt list to improve the user experience. You can set the style of the prompt list through CSS, for example:

#autocomplete-list {
  border: 1px solid #ccc;
  list-style: none;
  padding: 0;
  max-height: 200px;
  overflow-y: auto;
}

#autocomplete-list li {
  padding: 5px;
  cursor: pointer;
}

#autocomplete-list li:hover {
  background-color: #f1f1f1;
}
Copy after login

In the above example, we set the border style, list style, padding, maximum height and scroll bar of the prompt list.

Through the above steps, we can implement a simple auto-complete input box function. When the user enters a keyword, relevant data is automatically searched and matching items are displayed in the prompt list. Users can select and select an item through the mouse or keyboard to achieve automatic completion.

It should be noted that the above example is just a simple implementation, and the actual situation may require the cooperation of more complex processing logic and back-end interfaces. However, by understanding the above principles and examples, it can help us better implement and customize the auto-complete input box function.

The above is the detailed content of How to implement the automatic completion input box function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 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 do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

See all articles