The input input box realizes the association function

Reference URL http://www.jb51.net/article/28075.htm

 

The auto-complete function refers to: similar to Baidu search, after entering a part of a word, it will automatically prompt, and then the user can choose, and there is no need to enter the remaining part.

  The realization of this function requires the cooperation of the server. The client uses the script to display the data obtained from the server.

  First look at the HTML of the client:

copy code code show as below:
 
<!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>搜索词自动完成</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( ){ 
//Get the div layer 
var $search = $('#search'); 
//Get the input box JQuery object 
var $searchInput = $search.find('#search-text'); 
//Close the browser to provide Autocomplete of the input box 
$searchInput.attr('autocomplete','off'); 
//Create 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 the event, clear the drop-down list and hide when the input box loses focus 
$searchInput.blur(function(){ 
setTimeout(clear,500); 
}); 
//The index of the highlighted item in the drop-down list, when the drop-down is displayed When there is a list item, moving the mouse or the up and down keys of the keyboard will move the highlighted item, like Baidu search. 
var selectedItem = null; 
//timeout ID 
var timeoutid = null; 
//Set the highlighted background of the drop-down item 
var setSelectedItem = function(item){ 
//Update the index variable 
selectedItem = item ; 
//Press the up and down keys to display cyclically, if it is less than 0, it will be set to the maximum value, and if it is greater than the maximum value, it will be set to 0 
if(selectedItem < 0){ 
selectedItem = $autocomplete.find('li').length - 1; 

else if(selectedItem > $autocomplete.find('li').length-1 ) { 
selectedItem = 0; 

//First remove the height of other list items Brighten the background, 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', //The address of the 
server'data':{'search-text':$searchInput.val()}, //parameter'dataType 
':'json', //return Data type 
'type': 'POST', //Request type 
'success':function(data){ 
if(data.length) { 
//Traverse data and add it to the autocomplete area 
$.each(data, function(index, term) { 
//Create a li tag and add it to the drop-down list 
$('<li></li>').text(term).appendTo($autocomplete) 
.addClass('clickable') 
.  hover(function(){
//The event of each item in the drop-down list, the operation of moving the mouse in 
$(this).siblings().removeClass('highlight'); 
$(this).addClass('highlight'); 
selectedItem = index; 
},function(){ 
//The event of each item in the drop-down list, the operation of the mouse leaving 
$(this).removeClass('highlight'); 
// When the mouse leaves, the index is set to -1, as marked 
selectedItem = -1; 
}) 
.click(function(){ 
//If the mouse clicks on this item of the drop-down list, the value of this item is added to the input box In 
$searchInput.val(term); 
//Empty and hide the drop-down list 
$autocomplete.empty().hide(); 
}); 
});//Event registration is complete 
//Set the position of the drop-down list, and then display 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); 
//Display the drop-down list 
$autocomplete.show(); 


}); 
}; 
//Register an event to 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){ 
//up 
//selectedItem = -1 means the mouse leaves 
if(selectedItem == -1){ 
setSelectedItem($autocomplete.find( 'li').length-1); 

else { 
//Index minus 1 
setSelectedItem(selectedItem - 1); 

event.preventDefault(); 

else if(event.keyCode == 40) { 
//Next 
//selectedItem = -1 means the mouse leaves 
if(selectedItem == -1){ 
setSelectedItem(0 ); 

else { 
//Add 1 to the index 
setSelectedItem(selectedItem + 1); 

event.preventDefault(); 

}) 
.keypress(function(event){ 
//enter key 
if(event.keyCode == 13) { 
/ / The list is empty or the mouse leaves the 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 the window size change event, re-adjust the position of 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">请输入关键词</label><input type="text" id="search-text" name="search-text" /> 
<input type="button" id="submit" value="搜索"/> 
</div> 
</body> 
</html> 


For the server-side code, we choose JSP here, or PHP can be used, the server-side does not matter, the key is to transmit data. 

copy code code show as below:

<%@ 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); 


%> 


整个过程思路其实挺清晰的,首先在输入框上注册keyup事件,然后在事件中通过ajax获取json对象。取得数据后,每一项数据创建一个li标签,在标签上注册click事件,这样当我们点击每一项的时候,就可以响应事件。键盘导航的关键是记录当前高亮的索引值,根据索引值来调整背景高亮。显示下拉列表的位置要根据输入框的位置来设置,当浏览器的大小改变时,随时调整下拉列表的位置。 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326942585&siteId=291194637