PDA

View Full Version : Help with defining variable and assigning new value



dan0
01-06-2009, 05:29 PM
I have an ajax callback function that is supposed perform 2 tasks; the second task is what I need help with.

It is supposed to bind an anonymous function to the onkeypress event. This anonymous function is supposed to decrease or increase the value of a variable "p" based on if the up or down arrow key is pressed. The variable "p" is originally set to null and if the up key is pressed the value of p should be decreased by 1 and conversely if the down key is pressed the value of p should be increased by 1.

Currently, however, if the up key is pressed, regardless of how many times, the value of "p" is always 1 and if the down key is pressed, regardless of how many times, the value of "p" is always 0. Below is my code, can someone suggest/tell me where the problem in my code is? Thanks.



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

}
}