0

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.

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.