Home > Web Front-end > JS Tutorial > Baidu search-like input box auto-complete function implemented based on jquery_jquery

Baidu search-like input box auto-complete function implemented based on jquery_jquery

WBOY
Release: 2016-05-16 18:03:20
Original
1307 people have browsed it

Without further ado, let’s take a look at it intuitively:

Implementing this function requires the cooperation of the server. The client displays data obtained from the server through scripts.

First look at the HTML of the client:

Copy the code The code is as follows:
 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
 
 
 
搜索词自动完成 






For the server-side code, we choose JSP here, or you can use PHP. The server-side does not matter, the key is to transmit data.
Copy code The code is as follows:

<%@ page language="java" import= "java.util.*" pageEncoding="utf-8"%>
<%
String []words = {"amani","abc","apple","abstract","an ","bike","byebye",
"beat","be","bing","come","cup","class","calendar","china"};
if (request.getParameter("search-text") != null) {
String key = request.getParameter("search-text");
if(key.length() != 0){
String json="[";
for(int i = 0; i < words.length; i ) {
if(words[i].startsWith(key)){
json = " "" words[i] """ ",";
}
}
json = json.substring(0,json.length()-1>0?json.length()-1: 1);
json = "]";
System.out.println("json:" json);
out.println(json);
}
}
% >

The idea of ​​the whole process is actually quite clear. First, register the keyup event on the input box, and then obtain the json object through ajax in the event. After obtaining the data, create a li tag for each item of data and register the click event on the tag, so that when we click on each item, we can respond to the event. The key to keyboard navigation is to record the currently highlighted index value and adjust the background highlight based on the index value. The position of the drop-down list should be set according to the position of the input box. When the size of the browser changes, the position of the drop-down list can be adjusted at any time.
JQuery is a powerful tool for web front-end. If you have the chance, you must take a look.
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template