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:
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.
<%@ 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.