Reputation: 25
Im trying to write a simple autocomplete plugin for jquery (for learning purpose"). If u look at the DOM after the JS has run, there is to div after the input fields, but only the 2nd has the ul inside it. Why? it should be work identically on both input, shouldnt it?
http://jsbin.com/avomez/1/edit and Here is my code:
HTML
<input class="city" type="text" />
<input class="city" type="text" />
JS
$.fn.autocomplete = function(){
var self = $(this);
var drpd = $('<div class="dropdown" />');
var ul = $('<ul class="city" />');
self.after(drpd);
drpd.append(ul);
};
$("input.city").autocomplete();
Upvotes: 2
Views: 43
Reputation: 79830
You going to need to iterate and also return back the this
(jQuery object) to make a plugin. See below,
DEMO: http://jsbin.com/avomez/3/
Reason:
$('input.city')
return an array of elements, you should iterate on single elements to make sure you are not messing it up. Your original problem was a good example here.$('input.city').autocomplete().addClass('someclass');
Code:
$.fn.autocomplete = function(){
return this.each(function () {
var self = $(this);
var drpd = $('<div class="dropdown" />');
var ul = $('<ul class="city" />');
self.after(drpd);
drpd.append(ul);
});
};
Upvotes: 1
Reputation: 3437
Try using a change
event for finding the correct input:
$("input.city").change(function(){
$(this).autocomplete();
});
Upvotes: 0
Reputation: 3118
add this lines
$.fn.autocomplete = function(){
return this.each(function(){ //ADD
var self = $(this);
var drpd = $('<div class="dropdown" />');
var ul = $('<ul class="city" />');
self.after(drpd);
drpd.append(ul);
}); //ADD
};
Upvotes: 1