I have a textfield with drop down suggestion box. I created a plugin for the textfield to display search suggestions. But the keyup and blur events are not firing.
(function($){
$.fn.suggestions = function(input, suggestbox, options){
alert("page loaded");
alert(this.css("visibility"));
this.keyup(function(event){
alert(this.val());
if(this.val() != ""){
$(suggestbox).css("visibility", "visible");
alert($(suggestbox).css("visibility"));
$(suggestbox).hide();
$(suggestbox).fadeIn("fast");
var query = this.val();
$(suggestbox).empty();
$(suggestbox).append("<ul>").css({
'list-style-type': 'none',
'cursor': 'pointer'
});
input(query, function(companies){
$.each(companies, function(index, value){
$(suggestbox).append("<li>" + value + "</li>").children("li").mouseover(function(event){
$(this).removeClass(options.mouseoutcss);
$(this).addClass(options.mouseincss);
}).mouseout(function(){
$(this).removeClass(options.mouseincss);
$(this).addClass(options.mouseoutcss);
}).click(function(){
this.val($(this).text());
$(suggestbox).hide();
});
});
});
$(suggestbox).append("</ul>");
}else{
$(suggestbox).fadeOut("fast", function(){
$(suggestbox).css("visibility", "hidden");
});
}
});
this.blur(function(){
setTimeout(function(){
if($(suggestbox).css("visibility") == "visible"){
$(suggestbox).hide();
}
}, 200);
});
};
}) (jQuery);
I’ve also tried the following but no luck either.
this.each(function(){
$(this).keyup(function(event){....});
});
Cause
this.valis not a function in your keyup handler.thiswould refer to the html element, not a jQuery object. Your handler is being triggered, but it is throwing an error right at the start.Solution
Ensure that you are using a jQuery object where appropriate in your handlers. For example, change
this.valto$(this).val. I have created a jsFiddle demonstrating some of the required fixes. It will not completely work, as the code you gave was incomplete, but it should show you some of the corrections that are required.Notes
this, in the scope of the jQuery plugin, is a jQuery object.this, in the scope of an event handler, is an HTML element object.$(myHtmlElem), wheremyHtmlElemis an HTML element object.