Story so far.....
I want to learn JQuery, and im also building an MVC ASP.NET Apps which requires a "search as you type" search function - perfect to learn JQuery as well! So far (with the help of stackoverflowers ) I have managed to get the AJAX/JSON bit. Now I want to evaluate each key press and validate it against the JSON Array which was created as an unordered list. What im trying to achieve is to only show the account numbers in the list that contain what is inputted. So, my reasoning was to check against keydown event and validate it. For the time being im just changing the color of the account numbers to red of hiding them, just to prove my logic works.
My JQuery Code so far....
http://jsfiddle.net/garfbradaz/JYdTU/28/
...and for convenience....
$(document).ready(function() {
var $input = $("#livesearchinput"),
filled = false;
$.ajaxSetup({
cache: false
});
$input.keydown(function(key) {
if (!filled) {
filled = true;
$.getJSON("/gh/get/response.json//garfbradaz/MvcLiveSearch/tree/master/JSFiddleAjaxReponses/", function(JSONData) {
var $ul =
$('<ul>').attr({
id: "live-list"
}).appendTo('div#livesearchesults');
$.each(JSONData, function(i, item) {
$.each(item, function(j, val) {
$('<li>').attr({
id: "live-" + val
}).append(val).appendTo($ul);
});
});
});
}
var n = $("li:contains('" + this.value + "')").length;
if (n === 0) {
$("li").removeClass("color-change");
console.log("1. value of n equals " + n + " : " + this.value);
}
else {
$("li:contains('" + this.value + "')").addClass("color-change");
console.log("2. value of n equals " + n + " : " + this.value);
}
});
});
My Issue.....
My issue is that when i evaluate the key press using the following this.value is empty on the first keydown event and then out of step throughout
var n = $("li:contains('" + this.value + "')").length
Example:
If i input 100004, let me show you my console.log results from Chromefor inputting that result:
The results seem to always be one step behind. Is the keydown event the best one to use or am i missing something.
As always - thanks guys and happy coding.
Maybe the check fires before the AJAX part has completed.
Mind that AJAX is asynchronous and the code continues its flow regardless of the AJAX request, that is completed asynchronously.
Try to move the logic inside
function(JSONData)
.because
this.value
on the keydown event does not contain the keystoke which triggered the event. Use keyup instead.You can access the keystoke via the event object which is available in the function... but the value of the input will not contain it until the key is released.
http://jsfiddle.net/rlemon/TGBUe/1/ in this example you can open your console... and type a character in the input... you will notice the keydown this.value is blank for the first char whereas the keyup contains it.