Jump to content

Help with auto suggest


Dan06

Recommended Posts

I need help finishing my auto suggest code; I need help positioning the suggestion list directly under the "To" text field and creating the ability to use the up and down keys to move from the "To" text field to the suggestion list.

 

At this point, the code takes what the user inputs in the "To" text field, posts those values and using php/mysql returns a (li) list of values that match the input. However, the suggestion list appears under the "To" text field label rather than the "To" text field box.

 

I've attached the html, javascript, and css code I've put together. Thanks for the help.

 

[attachment deleted by admin]

Link to comment
Share on other sites

I think you'll get a better resonse with the code just in code tags :P

 

// JavaScript Document



function lookup(inputString){

if (inputString.length == 0){

	// Hide the suggestion box

	$("#suggestionBox").hide();

} else {

		if (window.XMLHttpRequest){

		XMLHttpRequestObj = new XMLHttpRequest();

	} else if (window.ActiveXObject){

		XMLHttpRequestObj = new ActiveXObject("Microsoft.XMLHttp");

		}



	var params = "msgRecipient=" + inputString;



	if (XMLHttpRequestObj){

		var url = "messaging.php";

		XMLHttpRequestObj.open("POST", url, true);

		XMLHttpRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

		XMLHttpRequestObj.setRequestHeader("Content-length", params.length);

		XMLHttpRequestObj.setRequestHeader("Connection", "close");



		XMLHttpRequestObj.onreadystatechange = function(){

			if (XMLHttpRequestObj.readyState == 4 && XMLHttpRequestObj.status == 200){

				suggestionCallback(XMLHttpRequestObj.responseText);

				delete XMLHttpRequestObj;

			}	

		}

		XMLHttpRequestObj.send(params);

	}

}



function suggestionCallback(ajaxResponse){

	if (!ajaxResponse.match(/Error/i) && ajaxResponse != ""){

		$("#suggestionBox").show();

		var suggestions = document.getElementById("suggestionList");

		suggestions.innerHTML = ajaxResponse;

	} else {

		alert(ajaxResponse);

	}

} // end callback



} // end function lookup



function insertAfter( newElement, targetElement ){

var parent = targetElement.parentNode; 

if ( parent.lastChild == targetElement ){

	parent.appendChild( newElement ); 

} else {

	parent.insertBefore( newElement, targetElement.nextSibling );

}

}



$(document).ready(function(){



// Create the suggestion box

var suggestionBox = document.createElement("span");

suggestionBox.setAttribute("id", "suggestionBox");

suggestionBox.setAttribute("class", "suggestionBox");



// And add it after the input box

var msgRecipient = document.getElementById("msgRecipient");

insertAfter( suggestionBox, msgRecipient );



// Hide suggestion box on load

$("#suggestionBox").hide()



// Create the suggestion list

var suggestionList = document.createElement("ul");

suggestionList.setAttribute("id", "suggestionList");

suggestionList.setAttribute("class", "suggestionList");



// And add to the suggestion box

suggestionBox.appendChild(suggestionList);



var input = document.getElementById("msgRecipient");

input.onkeyup = function(){ lookup(this.value); };



});

 

 

I notice the following in your script

$(document).ready(function(){

 

That's typically jQuery are you using that?

There are tons of jQuery autocomplete scripts to download. Are you doing this to learn jQuery?

Link to comment
Share on other sites

Yes, you're right

 

$(document).ready(function(){...});

is jQuery and I am using it; I should have mentioned that I was using jQuery in my original post.

 

No, I am not doing this coding exercise to learn jQuery, but rather to increase my knowledge/understanding of javascript.

 

As you pointed out, there probably are jQuery autocomplete scripts I could download; but that would defeat the main purpose of this exercise. The main purpose is to create a working autocomplete code using mostly traditional js (rather than a library, i.e. jQuery or prototype). I used jQuery's dom ready function, because in my code I create elements on the fly so I needed to make sure certain dom elements were present. For another coding exercise I might create a generic dom ready function; but for now using a bit of jQuery made sense.

 

Furthermore, the code I attached has been combined from 3 separate files (1 html, 1 js, 1 css) into 1 file for convenience of downloading and viewing. 

 

Lastly, Dj Kat, do you mean by:

I think you'll get a better resonse with the code just in code tags :P
that I should use
<script></script>

rather than

<script type="text/javascript"></script>

?

 

Help and insight appreciated.

 

 

 

Link to comment
Share on other sites

 

Lastly, Dj Kat, do you mean by:

I think you'll get a better resonse with the code just in code tags :P
that I should use
<script></script>

rather than

<script type="text/javascript"></script>

?

 

Help and insight appreciated.

nah i meant post the code on the forum instead of including it.

for using up and down keys you can use the events in jquery

http://docs.jquery.com/Events

Link to comment
Share on other sites

I've made some progress with the code, but I'm having trouble with two aspects.

 

1. The following code is an ajax callback function, which inserts the responseText into the markup and binds an anonymous function to onkeypress. When the user presses the up or down arrows the current li position should be stored in variable p and adjusted based on the number of times up or down is pressed. The idea was that every time a new suggestion list is created/displayed the value of p would be returned to null. However, in my code, the code always returns the value of variable p to be 1 if up is pressed and 0 if down is pressed.

 

function suggestionCallback(ajaxResponse){
if (!ajaxResponse.match(/Error/i) && ajaxResponse != ""){
	$("#suggestionBox").show();
	var suggestionList = document.getElementById("suggestionList");
	suggestionList.innerHTML = ajaxResponse; 

	var inputBox = document.getElementById("msgRecipient");
	var li = suggestionList.getElementsByTagName("li");
	var p = null;

	inputBox.onkeypress = function(e){ 

		// If [TAB] or [ENTER] keys are pressed
		if ( e.keyCode == 9 || e.keyCode == 13 ){

		} else if ( e.keyCode == 38 ){ // If the up key is pressed, select the previouse user or the last user if at the beginning
			p = (p == null) ? li.length-1 : p-1;
			if (p < 0){ p = li.length-1; }
			alert("p: " + p);
			updatePos( li[p] ); 
		} else if ( e.keyCode == 40 ){ // if the down key is pressed, select the next user or the first user if at the end
			p = (p == null) ? 0 : p+1;
			if (p > li.length-1){ p = 0; }
			alert("p: " + p);
			updatePos( li[p] );
		}	

	}; // end binding of function to input.onkeypress

} else {
	alert(ajaxResponse);
}
} // end suggestionCallback 

 

2. The following combination of functions is supposed to remove a class from an li position and add a class to another li position depending on the value of variable p. Seemingly the problem is that the value of p and its resulting li[p] value is not being recognized in the functions that are supposed to perform the addition/removal of classes. Below is the code:

function addClass( target, theClass ){
target.setAttribute("class", theClass);
}

function removeClass( target, theClass ){
target.setAttribute("class", "");
}

// Change the highlight of the user that's currently selected
function updatePos( elem ) {
// Update the position to the currently selected element
var elementPos = elem;
// Get all the user li elements
var li = document.getElementById("suggestonBox").getElementsByTagName("li");
// Remove the 'cur' class from the currently selected one
for ( var i = 0; i < li.length; i++ ){
	removeClass( li[i], "suggestionLight" );
}
// And add the highlight to the current user item
addClass( elementPos, "suggestionLight" );

}

 

Help appreciated.

Link to comment
Share on other sites

There were 2 problems:

 

1.

 var p = null; 

was inside the callback function, it needed to be outside of the function

 

2. The word suggestion in

 document.getElementById("suggestionBox")... 

was misspelled.

 

Once the above two errors were fixed the code works fine.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.