JavaScript implements the automatic completion of the search box of 1

  • 2021-01-06 00:27:06
  • OfStack

In many search sites, there will be an autocomplete search box, so that users can find the search term they want. Help users quickly find the results they want. This way is more friendly. Therefore, it is more recommended to use.

First, let me show you the effect picture:

Implementing this function requires the cooperation of the server. The client presents the data from the server via a script.

First look at the client HTML:

The code is as follows:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title> Search terms are automatically completed </title> 
<style type="text/css"> 
#search{ 
text-align: center; 
position:relative; 
} 
.autocomplete{ 
border: 1px solid #9ACCFB; 
background-color: white; 
text-align: left; 
} 
.autocomplete li{ 
list-style-type: none; 
} 
.clickable { 
cursor: default; 
} 
.highlight { 
background-color: #9ACCFB; 
} 
</style> 
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
$(function(){ 
// achieve div layer  
var $search = $('#search'); 
// Get input field JQuery object  
var $searchInput = $search.find('#search-text'); 
// Turn off the autocomplete provided by the browser to the input box  
$searchInput.attr('autocomplete','off'); 
// Creates an autocomplete drop-down list to display the data returned by the server , Insert it after the search button and adjust the position when it is displayed  
var $autocomplete = $('<div class="autocomplete"></div>') 
.hide() 
.insertAfter('#submit'); 
// Clear the contents of the drop-down list and hide the drop-down list area  
var clear = function(){ 
$autocomplete.empty().hide(); 
}; 
// Register events, clear the drop-down list and hide when the input field loses focus  
$searchInput.blur(function(){ 
setTimeout(clear,500); 
}); 
// An index of highlighted items in a drop-down list. When displaying a drop-down list item, moving the up and down keys of the mouse or keyboard will move the highlighted items, just like in a Baidu search  
var selectedItem = null; 
//timeout the ID 
var timeoutid = null; 
// Sets the highlighted background of the drop-down item  
var setSelectedItem = function(item){ 
// Update index variables  
selectedItem = item ; 
// Pressing up and down is a loop, less than 0 If it's greater than that, it's greater than that 0 
if(selectedItem < 0){ 
selectedItem = $autocomplete.find('li').length - 1; 
} 
else if(selectedItem > $autocomplete.find('li').length-1 ) { 
selectedItem = 0; 
} 
// First remove the highlighted background of the other list items, and then highlight the background of the current index  
$autocomplete.find('li').removeClass('highlight') 
.eq(selectedItem).addClass('highlight'); 
}; 
var ajax_request = function(){ 
//ajax Server communication  
$.ajax({ 
'url':'/test/index.jsp', // Server address  
'data':{'search-text':$searchInput.val()}, // parameter  
'dataType':'json', // Return data type  
'type':'POST', // Request type  
'success':function(data){ 
if(data.length) { 
// traverse data , add to the autocomplete area  
$.each(data, function(index,term) { 
// create li The label , Add to the drop-down list  
$('<li></li>').text(term).appendTo($autocomplete) 
.addClass('clickable') 
.hover(function(){ 
// Drop down list each 1 Item events, mouse-over operations  
$(this).siblings().removeClass('highlight'); 
$(this).addClass('highlight'); 
selectedItem = index; 
},function(){ 
// Drop down list each 1 Items of events, mouse-off operations  
$(this).removeClass('highlight'); 
// Indexed when the mouse is away -1 , as a marker  
selectedItem = -1; 
}) 
.click(function(){ 
// Mouse click on this in the drop-down list 1 For the term, put this 1 The value of the item is added to the input box  
$searchInput.val(term); 
// Clear and hide the drop-down list  
$autocomplete.empty().hide(); 
}); 
});// Event registration completed  
// Sets the location of the drop-down list, and then displays the drop-down list  
var ypos = $searchInput.position().top; 
var xpos = $searchInput.position().left; 
$autocomplete.css('width',$searchInput.css('width')); 
$autocomplete.css({'position':'relative','left':xpos + "px",'top':ypos +"px"}); 
setSelectedItem(0); 
// Displays a drop-down list  
$autocomplete.show(); 
} 
} 
}); 
}; 
// Event registration for the input box  
$searchInput 
.keyup(function(event) { 
// Alphanumeric, backspace, space  
if(event.keyCode > 40 || event.keyCode == 8 || event.keyCode ==32) { 
// First delete the information in the drop-down list  
$autocomplete.empty().hide(); 
clearTimeout(timeoutid); 
timeoutid = setTimeout(ajax_request,100); 
} 
else if(event.keyCode == 38){ 
// on  
//selectedItem = -1  Mouse away  
if(selectedItem == -1){ 
setSelectedItem($autocomplete.find('li').length-1); 
} 
else { 
// The index decreases 1 
setSelectedItem(selectedItem - 1); 
} 
event.preventDefault(); 
} 
else if(event.keyCode == 40) { 
// Under the  
//selectedItem = -1  Mouse away  
if(selectedItem == -1){ 
setSelectedItem(0); 
} 
else { 
// The index adds 1 
setSelectedItem(selectedItem + 1); 
} 
event.preventDefault(); 
} 
}) 
.keypress(function(event){ 
//enter key  
if(event.keyCode == 13) { 
// The list is empty or the mouse is off resulting in no current index value  
if($autocomplete.find('li').length == 0 || selectedItem == -1) { 
return; 
} 
$searchInput.val($autocomplete.find('li').eq(selectedItem).text()); 
$autocomplete.empty().hide(); 
event.preventDefault(); 
} 
}) 
.keydown(function(event){ 
//esc key  
if(event.keyCode == 27 ) { 
$autocomplete.empty().hide(); 
event.preventDefault(); 
} 
}); 
// Register for window size changes and reposition the drop-down list  
$(window).resize(function() { 
var ypos = $searchInput.position().top; 
var xpos = $searchInput.position().left; 
$autocomplete.css('width',$searchInput.css('width')); 
$autocomplete.css({'position':'relative','left':xpos + "px",'top':ypos +"px"}); 
}); 
}); 
</script> 
</head> 
<body> 
<div id = "search"> 
<label for="search-text"> Please enter key words </label><input type="text" id="search-text" name="search-text" /> 
<input type="button" id="submit" value=" search "/> 
</div> 
</body> 
</html> 

The server side code, we choose JSP here, can also use PHP, the server side does not matter, the key is to transfer data.

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 whole process is pretty straightforward. First, register an keyup event in the input box, and then get an json object from ajax in the event. After we get the data, we create an 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 highlighting 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 browser size changes, adjust the position of the drop-down list at any time.

The above is this site to introduce the JavaScript search box automatic completion function (1), I hope to help you!


Related articles: