The following is a function I bind to certain input fields to create an auto complete, as described in the Learning jQuery book from PACT. It's the same function, only wrapped so I can bind it to whatever input field I want
- function autoCompleteFunction(tagInQuestion, ajaxFile) {
var $autocomplete = $('<ul class="autocomplete"></ul>').hide().insertAfter('#' + tagInQuestion);
var selectedItem = null;
var setSelectedItem = function(item) {
selectedItem = item;
if (selectedItem === null) {
$autocomplete.hide();
return;
}
if (selectedItem < 0) {
selectedItem = 0;
}
if (selectedItem >= $autocomplete.find('li').length) {
selectedItem = $autocomplete.find('li').length - 1;
}
$autocomplete.find('li').removeClass('selected').eq(selectedItem).addClass('selected');
$autocomplete.show();
};
var populateSearchField = function() {
$('#' + tagInQuestion).val($autocomplete.find('li').eq(selectedItem).text());
setSelectedItem(null);
};
$('#' + tagInQuestion).attr('autocomplete', 'off').keyup(function(event) {
//console.log(event.keyCode);
if (event.keyCode > 40 || event.keyCode == 8) {
//check if the input string is at least 3 characters
var stringLength = $('#' + tagInQuestion).val();
stringLength = stringLength.length;
if (stringLength >= 3) {
// Keys with codes 40 and below are special (enter, arrow keys, escape, etc.).
// Key code 8 is backspace.
$.ajax({
'url': 'http://www.mysite.com/ajax/' + ajaxFile,
'data': {'search-text': $('#' + tagInQuestion).val()},
'dataType': 'json',
'type': 'POST',
'success': function(data) {
if (data.length) {
$autocomplete.empty();
$.each(data, function(index, term) {
term = term.replace('&', '&');
term = term.replace('&', '&');
$('<li></li>').text(term).appendTo($autocomplete).mouseover(function() {
setSelectedItem(index);
}).click(populateSearchField);
});
setSelectedItem(0);
}
else {
setSelectedItem(null);
}
}
});
}
}
else if (event.keyCode == 38 && selectedItem !== null) {
// User pressed up arrow.
setSelectedItem(selectedItem - 1);
event.preventDefault();
}
else if (event.keyCode == 40 && selectedItem !== null) {
// User pressed down arrow.
setSelectedItem(selectedItem + 1);
event.preventDefault();
}
else if (event.keyCode == 27 && selectedItem !== null) {
// User pressed escape key.
setSelectedItem(null);
}
}).keypress(function(event) {
if (event.keyCode == 13 && selectedItem !== null) {
// User pressed enter key.
populateSearchField();
event.preventDefault();
}
}).blur(function(event) {
setTimeout(function() {
setSelectedItem(null);
}, 250);
});
};
It worked great until I upgraded to jQuery 1.4. Now the autocompletes no longer work.
My Error Console gives me following error:
The 'charCode' property of a keydown event should not be used. The value is meaningless.
I suppose this has to do with the event.keyCode used, but my knowledge of both JS and jQ are for now a bit too limited.