Home Web Front-end JS Tutorial Automatically complete search box javascript implementation_javascript skills

Automatically complete search box javascript implementation_javascript skills

May 16, 2016 pm 03:13 PM
js search bar

In many websites that need to be searched, there will be an auto-complete search box. It is convenient for users to find the search terms they want. It helps users quickly find the results they want. This method is more friendly. So it is more It is recommended to use.

We will achieve this effect this time. We will explain it through two articles. First, we will complete the design and layout of the interface.

The HTML structure of the interface, the first one is a search box, and the second one is the search click button.

 <div class="search">
     <input type="text" value="">
     <button>搜索</button>
 </div>
Copy after login

This is the simplest search box design. How to deal with the CSS code. In the past, float was used for processing, and then the search box was given a border and a padding was set. Then the border was removed for the button and a padding was set. Background. Here we use flex layout. This is simpler. There is no need to consider clearing the floating effect. Of course, compatibility issues must be considered here.

.search {
  display: inline-flex;
  height: 35px;
  margin: 50px auto;
  position: relative;
}
.search input {
  border: #eee 1px solid;
  background-color: #fff;
  outline: none;
  width: 200px;
  padding: 0 5px;
}
.search button {
  background-color: #ff3300;
  color: #fff;
  border: none;
  width: 80px;
}
Copy after login

At this time we continue to think about it. If the user enters a keyword, a list of related words must be displayed. Then we need to add a word list at this time.
For example

<ul>
  <li><a href="#">武林外传</a> </li>
  <li><a href="#">葵花宝典</a> </li>
  <li><a href="#">如来佛掌</a> </li>
  <li><a href="#">九阴白骨爪</a> </li>
</ul>
Copy after login

We append this line of code to the content of .search. Then set the CSS code. We set its minimum width to the width of .search minus the width of the search button. This will be the same width as the search box.

.search ul {
  position: absolute;
  left: 0;
  top: 35px;
  border: #eee 1px solid;
  min-width: calc(100% - 80px);
  text-align: left;
}
.search ul a {
  display: block;
  padding: 5px;
}

Copy after login

This requires clearing some default browser styles before the CSS code. The final effect is as follows.

Okay. Now let’s complete the JS code control.
Let's analyze the events. After the user enters text in the input box, the entered text is queried with the background data. After the query is obtained, it is returned to the client, and then the returned data is displayed under the data list.

According to this step, we first get the input box label and add the onkeyup event to this label

 var ele_key = document.getElementById("key");
 ele_key.onkeyup = function (e) {
   //处理事件
 }
Copy after login

Here we simulate a background data, represented here by data, and then add some data

var data = ["编程的人", "武林外传", "葵花宝典", "九阴白骨爪", "武林江湖", "will"];
Copy after login

The background data is available and events are added. Now we process the data.
The first is to obtain the input data, and then compare it with the background data. Then save the compared data in a data.

//定义一些数据
var data = ["编程的人", "武林外传", "葵花宝典", "九阴白骨爪", "武林江湖", "will"];
var ele_key = document.getElementById("key");
ele_key.onkeyup = function (e) {

  var val = this.value;

  //获取输入框里匹配的数据
  var srdata = [];
  for (var i = 0; i < data.length; i++) {
    console.log(data[i].indexOf(val))
    if (val.trim().length > 0 && data[i].indexOf(val) > -1) {
       srdata.push(data[i]);
    }
  }

 }
Copy after login

Continue to analyze. At present, after we obtain the data queried in the background, we have to display this data to the user for viewing. Here we display it in the data list.

//定义一些数据
var data = ["编程的人", "武林外传", "葵花宝典", "九阴白骨爪", "武林江湖", "will"];
var ele_key = document.getElementById("key");
ele_key.onkeyup = function (e) {

  var val = this.value;

  //获取输入框里匹配的数据
  var srdata = [];
  for (var i = 0; i < data.length; i++) {
    console.log(data[i].indexOf(val))
    if (val.trim().length > 0 && data[i].indexOf(val) > -1) {
       srdata.push(data[i]);
    }
  }

 //获取到的数据准备追加显示, 前期要做的事情: 清空数据,然后显示数据列表,如果获取到的数据为空,则不显示
  var ele_datalist = document.getElementById("datalist");
  ele_datalist.style.visibility = "visible";
  ele_datalist.innerHTML = "";

  if (srdata.length == 0) {
    ele_datalist.style.visibility = "hidden";
  }

  //将搜索到的数据追加到显示数据列表, 然后每一行加入点击事件, 点击后将数据放入搜索框内, 数据列表隐藏
  var self = this;
  for (var i = 0; i < srdata.length; i++) {
    var ele_li = document.createElement("li");
    var ele_a = document.createElement("a");
    ele_a.setAttribute("href", "javascript:;");
    ele_a.textContent = srdata[i];

    ele_a.onclick = function () {
       self.value = this.textContent;
      ele_datalist.style.visibility = "hidden";
    }


    ele_li.appendChild(ele_a);
    ele_datalist.appendChild(ele_li);
  }

 }

Copy after login

When adding data to the list, we first initialize the data list to avoid adding duplicate data. Secondly, we add a click event to each row of the data list, and put the data into the search box after clicking. , the data list is hidden.

The entire auto-complete search box is completed here. Let’s test the effect.

This may be a problem with the recording software. The border should be the same color as the background it was recorded on. The border is missing (⊙﹏⊙)b
The above is the automatic completion effect of the search box implemented by JAVASCRIPT. You can test it yourself!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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 use JS and Baidu Maps to implement map pan function How to use JS and Baidu Maps to implement map pan function Nov 21, 2023 am 10:00 AM

How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to set the Windows 10 search bar to be transparent How to set the Windows 10 search bar to be transparent Jan 09, 2024 pm 09:46 PM

Some users see that the win10 search box is transparent, and they want to have it, but they don’t know how to set it. Now there is a very simple method. Just download the software from the win10 store. Let’s take a look at how to set the win10 search box to be transparent. method. The win10 search box is transparent: 1. Right-click the taskbar and select Search to turn the search box into a search icon. 2. Open the app store. 3. Search for TranslucentTB software. (You can choose to download the Chinese version) 4. After downloading and installing. 5. Open TranslucentTB, which can be seen in the taskbar on the lower right. 6. Set it to fully transparent.

How to solve the problem that the win10 search box is grayed out and cannot be used How to solve the problem that the win10 search box is grayed out and cannot be used Jan 03, 2024 am 11:07 AM

When users daily use the win10 search box to search for content and required software, they find the problem that the win10 search box is gray and cannot be used. Generally, it is set to disabled in the computer policy group. Let’s take a look at the solution to the win10 search box that is gray and cannot be used. method. The win10 search box is gray and cannot be used. Solution: 1. Press the win+R keys to open the run and enter gpedit.msc. 2. In the Local Group Policy Editor - select Administrative Templates - Windows Components option. 3. Find the Search-Allow Cortana option. 4. After opening, select Disabled on its page, click OK, and restart the computer.

How to use JS and Baidu Maps to implement map heat map function How to use JS and Baidu Maps to implement map heat map function Nov 21, 2023 am 09:33 AM

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

See all articles