user2460608
user2460608

Reputation: 25

Jquery plugin behave different on different instances

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

Answers (3)

Selvakumar Arumugam
Selvakumar Arumugam

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:

  1. The $('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.
  2. Returning jQuery object allows you to chain like $('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

ckpepper02
ckpepper02

Reputation: 3437

Try using a change event for finding the correct input:

$("input.city").change(function(){
     $(this).autocomplete();
});

Upvotes: 0

Abraham Uribe
Abraham Uribe

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

Related Questions