thanikkal
thanikkal

Reputation: 3356

How to keep the reference to the original object that invoked a jquery plug in?

I am creating a jquery plugin that adds a help text icon next to the element its being called on. How do I get a reference to the original input/textarea object on which the plugin method was callled?

Here is the code:

 <input text name="name" data-help-text="Enter your name here" class="helpon">
    <input text name="age" data-help-text="Enter your age here" class="helpon">
    <textarea name="experience" data-help-text="Enter a short summary of your experience" class="helpon"> </textarea>


    <script type="text/javascript">
    $(document).on("ready", function() {

        $.fn.showHelp = function() {
            return this.each(function() {
                self = $(this)
                var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
                icon.on("click", function(){ 
                 //how do i get a reference to the input/textarea here on which this? 
                    alert( self.data("help-text") )
                });
                self.after(icon);
            });
        };


      $('.helpon').showHelp();
    });


    </script>

how do i get a reference to the input/textarea on the icon click event? self is referring to the last object in the objects array (textarea in this case)

Upvotes: 2

Views: 124

Answers (2)

CodingIntrigue
CodingIntrigue

Reputation: 78525

You need to give a scope to the self variable:

$.fn.showHelp = function() {
            return this.each(function() {
                var self = $(this)
                var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
                icon.on("click", function(){ 
                 //how do i get a reference to the input/textarea here on which this? 
                    alert( self.data("help-text") )
                });
                self.after(icon);
            });
        };


      $('.helpon').showHelp()

Upvotes: 1

Ashis Kumar
Ashis Kumar

Reputation: 6544

You can use the event object to get the target element.

var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>')
icon.on("click", function(){ 
    // you can use the target of the event object 
    alert( $(e.target).data("help-text") )
});

you can get details over here

Upvotes: 0

Related Questions