Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Wagner Martins - SC

Auto sugestão

Recommended Posts

Olá,

 

 

Estou fazendo um script em javascript para quando o usuario do site estiver digitando uma pesquisa aparece embaixo sugestões da letra ou palavra que ele esta procurando puxando do banco de dados.

 

Pois bem, eu já consegui fazer com que ele busque no banco de dados e aparece em baixo.

 

Minha dúvida é que quando o usuario do site clica na palavra que aparece essa palavra não vai para dentro do input, como eu poderia fazer isso?

 

<!-- AJAX AUTOSUGGEST SCRIPT -->
<script type="text/javascript" src="lib/ajax_framework.js"></script>

<style type="text/css">
/* ---------------------------- */
/* CUSTOMIZE AUTOSUGGEST STYLE	*/
#search-wrap input{width:400px; font-size:16px; color:#999999; padding:6px; border:solid 1px #999999;}
#results{width:260px; border:solid 1px #DEDEDE; display:none;}
#results ul, #results li{padding:0; margin:0; border:0; list-style:none;}
#results li {border-top:solid 1px #DEDEDE;}
#results li a{display:block; padding:4px; text-decoration:none; color:#000000; font-weight:bold;}
#results li a small{display:block; text-decoration:none; color:#999999; font-weight:normal;}
#results li a:hover{background:#FFFFCC;}
#results ul {padding:6px;}
</style>
<div id="search-wrap">
<h1>Search with Auto Suggest</h1>
<input name="search-q" id="search-q" type="text" onkeyup="javascript:autosuggest()"/>
<div id="results"></div>
</div>

 

<?php 
	// ---------------------------------------------------------------- // 
	// DATABASE CONNECTION PARAMETER 									// 
	// ---------------------------------------------------------------- // 
	// Modify config.php with your DB connection parameters or add them //
	// directly below insted of include('config.php'); 					//
	
	include('config.php'); 
	
	
	// ---------------------------------------------------------------- // 
	// SET PHP VAR - CHANGE THEM										// 
	// ---------------------------------------------------------------- // 
	// You can use these variables to define Query Search Parameters:	//
	
	// $SQL_FROM:	is the FROM clausule, you can add a TABLE or an 	//
	// 				expression: USER INNER JOIN DEPARTMENT...			//
	
	// $SQL_WHERE	is the WHER clausule, you can add an table 	 		//
	// 				attribute for ezample name or an 					//
	
	
	$SQL_FROM = 'hoteis';
	$SQL_WHERE = 'destino';

?>
<?php
	$searchq		=	strip_tags($_GET['q']);
	$getRecord_sql	=	'SELECT * FROM '.$SQL_FROM.' WHERE '.$SQL_WHERE.' LIKE "'.$searchq.'%"';
	$getRecord		=	mysql_query($getRecord_sql);
	if(strlen($searchq)>0){
	// ---------------------------------------------------------------- // 
	// AJAX Response													// 
	// ---------------------------------------------------------------- // 
	
	// Change php echo $row['name']; and $row['department']; with the	//
	// name of table attributes you want to return. For Example, if you //
	// want to return only the name, delete the following code			//
	// "<br /><?php echo $row['department'];></li>"//
	// You can modify the content of ID element how you prefer			//
	echo '<ul>';
	while ($row = mysql_fetch_array($getRecord)) {?>
		<li><a href="#"><?php echo $row['destino']; ?></a></li>
	<?php } 
	echo '</ul>';
	?>
<?php } ?>
/* ---------------------------- */
/* XMLHTTPRequest Enable 		*/
/* ---------------------------- */
function createObject() {
	var request_type;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
	request_type = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		request_type = new XMLHttpRequest();
	}
		return request_type;
}

var http = createObject();

/* -------------------------- */
/* SEARCH					 */
/* -------------------------- */
function autosuggest() {
q = document.getElementById('search-q').value;
// Set te random number to add to URL request
nocache = Math.random();
http.open('get', 'lib/search.php?q='+q+'&nocache = '+nocache);
http.onreadystatechange = autosuggestReply;
http.send(null);
}
function autosuggestReply() {
if(http.readyState == 4){
	var response = http.responseText;
	e = document.getElementById('results');
	if(response!=""){
		e.innerHTML=response;
		e.style.display="block";
	} else {
		e.style.display="none";
	}
}
}

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

vc tem q disparar uma função no evento onclick dos teus lis, pegando o .innerHTML deles, e jogando para dentro do .value do input.

Compartilhar este post


Link para o post
Compartilhar em outros sites

aqui vc coloca o response, certo ?

		e.innerHTML=response;
		e.style.display="block";

ai vc tem q disparar a função:

 

 

Foi isso aqui que eu disse:

	e.innerHTML=response;
	e.style.display="block";
	
	var lis = e.getElementsByTagName('li');
	for( var i=0; i<lis.length; i++ )
	{
		lis[i].onclick = function(){
			document.getElementById('search-q').value = this.innerHTML;
		}
	}

Compartilhar este post


Link para o post
Compartilhar em outros sites

Beleza, deu certo, só que quando clico na palavra q aparece na sugestão ele vai para o input mais a sugestão de busca ainda fica aparecendo. Tem como depois de clicar na sugestão da busca ele desaparecê?

Compartilhar este post


Link para o post
Compartilhar em outros sites

sim, uê...

 

só vc dar o display none depois de colocar o input:

		lis[i].onclick = function(){
			document.getElementById('search-q').value = this.innerHTML;
			e.style.display="none";
		}
:lol:

Compartilhar este post


Link para o post
Compartilhar em outros sites

function autosuggest() {

var q = document.getElementById('search-q').value;

if( q.length>=3 ) {

// Set te random number to add to URL request

 

// o codigo aqui dentro

}//fecha o if

}

entendeu ?

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.