[jQuery] making style changes on keydown event
Hi All,
I am new to jQuery and need some help.
I am writing a custom suggest box in jQuery. One behavior I am trying
to achieve is highlight suggestions on keydown on keyup events.
I have written css classes for it and I am using toggleClass in event
handler. But problem I am facing is that the style changes are done as
long as event is live. Let me explain it, I am changing background-
color on keydown event, the color changes on keydown event but as soon
as I release key the background-color gets back to original value.
I want the style changes to be permanent until I change them on some
other event/criteria.
Let me provide my jQuery code -
$(
function() {
$("#fromCityBox")
.keyup(
function(event) {
event.preventDefault();
var value = $(this).val();
if(value.length >= 3) {
$.ajax(
{
type : "GET",
url : "/etravel_new/suggest.do?for=" +value,
success : function(response) {
if(response && response.length > 0) {
$("#fromSuggestionsTable")
.html(response)
.css("display", "block")
.filter("#fromSuggestionsTable td")
.click(
function(event) {
if($(event.target).is("td")) {
$("#fromCityBox").val($(event.target).text());
var code = getAirportCode($(event.target).text());
$("#from_CityF").val(code);
};
$("#fromSuggestionsTable").css("display", "none");
}
)
.mouseover(
function(event) {
$(event.target).toggleClass("highlightSuggestion");
}
)
.mouseout(
function(event) {
$(event.target).toggleClass("highlightSuggestion");
}
);
}
else {
$("#fromSuggestionsTable")
.css("display", "none");
}
}
}
);
}
if(value.length < 3) {
$("#fromSuggestionsTable").css("display", "none");
}
}
)
.click(
function(event) {
event.preventDefault();
}
);
}
);
$(
function() {
$("#fromCityBox")
.add("#fromSuggestionsTable td")
.keydown(
function(event) {
var key = getKeyCode(event);
var tableDisplay = $("#fromSuggestionsTable").css("display");
if(tableDisplay && tableDisplay != 'none') {
if(key == 38) {
alert("up ... up ... up");
}
else if(key == 40) {
//$("#fromSuggestionsTable td").slice(suggestBoxIndex,
suggestBoxIndex + 1).toggleClass("highlightSuggestion");
$("#fromSuggestionsTable td").slice(suggestBoxIndex,
suggestBoxIndex + 1).css("background-color", "#AFEEEE");
suggestBoxIndex++;
}
}
}
);
}
);
* fromCityBox is input field on which I am showing suggestions
* fromSuggestionsTable is the table which is container of ajax
response sent from server side, which are actually <tr><td>sugg1</td></
tr>s.
Please guide me on this problem.
Regards,
Ajay