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.