I am attempting to capture user input using jquery and the keydown event.
Here's my c开发者_开发百科ode:
$(document).ready(function() {
$("#searchText").keydown(function() {
var filter = jQuery.trim($(this).val());
if (filter.length > 3 || filter.length == 0) {
//hit the index action again and pass the keyword
$("#results").fadeOut("fast");
$("#results").load("/Organisation/Index?keyword=" + filter, null, function() {
$(this).fadeIn("fast");
});
}
});
});
At the mo this is working, aside from the fact that the string captured always seems to be 'out of date' by one character and I have to press another key to actually get the text I want passed to my action.
Thanks in advance!
You problem is the 'keydown' event. Since the processing of the value is done when key is press down which the newly pressed character is not yet accounted to the input. By using 'keyup', the processing is done after the newly pressed character is already added to the value.
$(document).ready(function() {
$("#searchText").keyup(function() {
var filter = jQuery.trim($(this).val());
if (filter.length < 3 || filter.length == 0) {
//hit the index action again and pass the keyword
$("#results").fadeOut("fast");
$("#results").load("/Organisation/Index?keyword=" + filter, null, function() {
$(this).fadeIn("fast");
});
}
});
});
You can also try using the bind method to catch other "key stroke" events like so:
$("#searchText").bind("keyup click blur focus change paste", function(){
//stuff
});
精彩评论