Reputation: 1288
this is my first time creating plugin. But my plugin have some little issue. I have created a simple replica of my plugin below
$.fn.myPlugin = function(url){
return this.each(function() {
element = $(this);
$.getJSON(url, function(response){
elem.val(response.init_value);
});
});
}
and Initiated Like this
$("#test1").myPlugin('/get1.json'); //this should value 1
$("#test2").myPlugin('/get2.json'); //this should value 2
but the result is not working as expected
Element #test1 has done nothing, no value (I think it is broken)
Element #test2 has value of 2
My plugin is working fine when i initiate a single instance but when im trying to make a multiple instances, only the last instance is working.
Upvotes: 0
Views: 285
Reputation: 1028
I think this occurs because you've declared element
without using var
.
This way you've declared element
as a global variable, so element = $(this);
is basically the same as window.element = $(this);
. Because of this, the second function call will overwrite the first instance of element
.
That should be a simple fix: var element = $(this);
Upvotes: 1