Need some help on an Ajax autosuggest problem

Autosuggest is already working, I can't make the up/down arrows wo

Page 1 of 1

4 Replies - 2612 Views - Last Post: 02 November 2009 - 05:53 PM

#1 NoPantsJim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 22-July 09

Need some help on an Ajax autosuggest problem

Posted 31 October 2009 - 11:57 PM

I'm fairly good with PHP and MySQL at this point, but I have never done anything with Javascript other than pasting Google Analytics into my footer. I knew this would be a challenge when I set out to do it, but fortunately I have nearly everything working. The last thing I have been unable to piece together from various web tutorials is the ability for users to scroll items in my autosuggest dropdown by using the up/down arrows, and then hitting enter to submit the selected option.

Here's the code on the page:

echo	'<link href="/ajax.css" rel="stylesheet" type="text/css" media="screen" />
		<script type="text/javascript" src="jquery-1.2.1.pack.js"></script>
		<script type="text/javascript">
			function lookup(inputString) {
				if(inputString.length == 0) {
					// Hide the suggestion box.
					$(\'#suggestions\').hide();
				} else {
					$.post("ajax.php", {queryString: ""+inputString+""}, function(data){
						if(data.length >0) {
							$(\'#suggestions\').show();
							$(\'#autoSuggestionsList\').html(data);
						}
					});
				}
			} // lookup
			
			function fill(thisValue) {
				$(\'#inputString\').val(thisValue);
				setTimeout(function () { $(\'#suggestions\').hide(); }, 200);
			}
		</script>



and here's what is in in the form:

<input type="text" size="50" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" name="movie" autocomplete="off"/>



and the ajax.php backend:

<?php

include('/home/nopantsjim/MySql/The_Maltin_Game_Mysqli_Connect.php');

if(isset($_POST['queryString']))
	{
	$queryString = scrub_sql_data($_POST['queryString']);

	if(strlen($queryString) > 0)
		{
		$queryString = '%' . $queryString . '%';

		$query="SELECT
				DISTINCT
				title
				FROM
				movie_titles
				WHERE
				title
				LIKE
				?
				ORDER BY
				title
				ASC LIMIT 7";
		$stmt = mysqli_prepare($dbc, $query);
		mysqli_stmt_bind_param($stmt, "s", $queryString);
		mysqli_stmt_execute($stmt);
		mysqli_stmt_bind_result($stmt, $title);
		mysqli_stmt_store_result($stmt);

		$num_results = mysqli_stmt_num_rows($stmt);

		if($num_results > 0)
			{
			while(mysqli_stmt_fetch($stmt))
				{
				echo '<li onclick="fill(\'' . $title . '\');">' . $title . '</li>';
				}
			}
		else
			{
			echo	'&nbsp;&nbsp;* No Matching Movie Titles *';
			}

		mysqli_stmt_close($stmt);
		}
	}
else
	{
	$url = 'http://' . $_SERVER['HTTP_HOST'] . '/';

	header("Location: $url");
	exit();
	}

?>



Here's the CSS for the box, in case it matters:

.suggestionsBox
{
position: relative;
left: 0px;
margin: 10px 0px 0px 115px;
width: 315px;
background-color: #000;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
border: 2px solid #000;
color: #fff;
}

.suggestionList li
{
list-style: none;
padding: 0px 0px 0px 7px;
cursor: pointer;
-moz-border-radius: 7px;
-webkit-border-radius: 7px;
}

.suggestionList li:hover
{
/* background-color: #659CD8; */
background-color: #0033FF;
}



The actual page where all of this is located is http://TheMaltinGame.com/play

This post has been edited by NoPantsJim: 01 November 2009 - 12:48 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Need some help on an Ajax autosuggest problem

#2 Aligator301  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 01-November 09

Re: Need some help on an Ajax autosuggest problem

Posted 02 November 2009 - 07:03 AM

Hello!

You'll probably be wanting to make that suggestion box Absolutely positioned (otherwise it changes your layout and I presume you don't want to)

Basically what you'll probably need to do is move the focus from your input box To your floating list, you can then have some jQuery hooks on 'keydown' or up to look for the arrows being used. I would probably attach this to the UL element, in the function that deals with the key press I would then find the next or prev sibling and highlight it (adding another class to show which one is selected).
I would expect it to look something roughly like this (oh, have a look here: http://docs.jquery.c...raversing/next)



<script type="text/javascript">
jQuery('#filmDropDown').keyup(function(event){
	var selectedEle = jQuery('#filmDropDown .selected');
	
	if (event.keyCode == enterkey... can't remember the code no.)
	{
		add the current selected list item's text value to the input box
		jQuery(input box).text(  selectedEle.text() );
		return;
	}
	
	if (selectedEle && selectedEle.eq(0))
	{
	
		if (event.keyCode == 38) {
		// up
			if (selectedEle.next())
			{
				selectedEle.removeClass('selected');
				selectedEle.next().addClass('selected');
			}
		}
		if (event.keyCode == 40) {
		// down
		}   
	}
	else 
	{
		var firstElement = jQuery('#filmDropDown li').eq(0);		
		if (firstElement)
		{
			firstElement.addClass('selected');
		}
	}
});
</script>



<ul id="filmDropDown">
	<li class="selected">film 1</li>
	<li>film 2</li>
	<li>film 3</li>
	<li>film 4</li>
</ul>




I don't have enough time to shoot out a perfect example but this should get you started...

A.
Was This Post Helpful? 1
  • +
  • -

#3 NoPantsJim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 22-July 09

Re: Need some help on an Ajax autosuggest problem

Posted 02 November 2009 - 02:25 PM

The relative positioning does push the footer down whenever the dropdown is open, however I currently have ads turned off. The advertisement on the right hand side pushes the footer down far enough that the dropdown menu does not affect it at all.

Thanks for the code, but I find myself scratching my head even more. I'm not sure why I'm having so much trouble learning javascript, as PHP was extremely easy for me to pick up. It seems the more I read about Javascript, the more confused I get. Time to hit the books again.
Was This Post Helpful? 0
  • +
  • -

#4 Aligator301  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 01-November 09

Re: Need some help on an Ajax autosuggest problem

Posted 02 November 2009 - 03:55 PM

What boggles you?

I've just completed a nice example for you, it was kinda fun.

Only tested and known to work in firefox (because that is where firebug is)
Works with up/down keys and mouse

Have fun!

Time for bed :D

<html>
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
	<style type="text/css">
	
		html, body, div, span, applet, object, iframe,
		h1, h2, h3, h4, h5, h6, p, blockquote, pre,
		a, abbr, acronym, address, big, cite, code,
		del, dfn, em, font, img, ins, kbd, q, s, samp,
		small, strike, strong, sub, sup, tt, var,
		b, u, i, center,
		dl, dt, dd, ol, ul, li,
		fieldset, form, label, legend,
		table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; }
		body { line-height: 1;}
		ol, ul { list-style: none;}
		blockquote, q { quotes: none;}
		blockquote:before,  blockquote:after,  q:before, q:after { content: '';content: none; }
		:focus { outline: 0; }
		ins { text-decoration: none; }
		del { text-decoration: line-through; }
		table { border-collapse: collapse;border-spacing: 0; }


		body { background: #fff; /*font: 62.5% Helvetica, Arial, sans-serif;*/ font: 10px Helvetica, Arial, sans-serif; text-align: center; }
		hr { display: none; }
		strong { font-weight: bold; }
		em { font-style: italic; }
		abbr, acronym { border: none; cursor: help; }
		input, textarea, select { font: 1em Helvetica, Arial, sans-serif; }
		input.checkbox {font-size:12px;}
		a { color: #000; text-decoration: none; }
		a:hover, a:active { color: #000; text-decoration: underline; }
		
		.filmDropDown {display:none; position:absolute; left:2px; top:20px; background-color:#eee; width:150px;}
		
		#dropDownHolder {position:relative;top:0; left:0; text-align:left;}
		
		#dropDownHolder .vis {display:block;}
		myInput {text-align:left;}
	
		.selected {background-color:green;}
	</style>
</head>

<body>

	<script type="text/javascript">
		$(document).ready(function() {
		
			jQuery('.filmDropDown li').click(function() {
				insertSelectedElement(jQuery(this));
			});
			
			jQuery('.filmDropDown li').hover(function(){
				jQuery(this).addClass('selected');
			}, function(){
				var selectedEle = jQuery('.filmDropDown .selected');
				if (selectedEle)
				{
					selectedEle.removeClass('selected');
				}
			});
		
			jQuery('.myInput').keyup(function(event) {
			
				lookupList();
				
				if (jQuery(this).val().length>0)
				{
					jQuery('.filmDropDown').addClass('vis');
				}
				else
				{
					jQuery('.filmDropDown').removeClass('vis');
				}
				
				if (event && event.which) { //if which property of event object is supported (NN4)
					characterCode = event.which //character code is contained in NN4's which property
				} else {
					characterCode = event.keyCode //character code is contained in IE's keyCode property
				}

				var selectedEle = jQuery('.filmDropDown .selected');
				
				if (characterCode == 13 && selectedEle.length>0)
				{
					//add the current selected list item's text value to the input box
					insertSelectedElement(selectedEle);
					
				} else if (characterCode == 38 && selectedEle.length>0) {
					// up
					selectedEle.removeClass('selected');
					if (selectedEle.prev().length>0)
					{
						selectedEle.prev().addClass('selected');
					}
					else
					{
						if (jQuery('.filmDropDown li').length>0)
						{
							var firstElement = jQuery('.filmDropDown li').eq( jQuery('.filmDropDown li').length-1 );	
							if (firstElement)
							{
								firstElement.addClass('selected');
							}
						}
					}
					
				} else if (characterCode == 40 && selectedEle.length>0) {
					// down
					selectedEle.removeClass('selected');
					if (selectedEle.next().length>0)
					{
						selectedEle.next().addClass('selected');
					}
					else
					{
						var firstElement = jQuery('.filmDropDown li').eq(0);	
						if (firstElement)
						{
							firstElement.addClass('selected');
						}
					}					
				} else {
					var firstElement = jQuery('.filmDropDown li').eq(0);	
					if (firstElement)
					{
						firstElement.addClass('selected');
					}
				}
			});
		});

		
		function lookupList()
		{
			// you need to repopulate the list elements with the latest list, here.
			/*
			
				HERE BE PIRATES! ! !
			
			*/
		}
		
		function insertSelectedElement(Element)
		{
			if (Element && Element.length>0)
			{
				jQuery('.myInput').val(Element.eq(0).text());
				jQuery('.filmDropDown').removeClass('vis');
			}
		}
		
	</script>

	

	<div id="dropDownHolder">
		<input class="myInput" type="text" name="cheese" />
		<ul class="filmDropDown">
			<li>film 1</li>
			<li>film 2</li>
			<li>film 3</li>
			<li>film 4</li>
		</ul>
	</div>

</body>

</html>



Was This Post Helpful? 0
  • +
  • -

#5 NoPantsJim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 22-July 09

Re: Need some help on an Ajax autosuggest problem

Posted 02 November 2009 - 05:53 PM

Thanks, that code gives me a ton of good info to work with. I'll report back in about 24 hours with any progress.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1