Hassen
Hassen

Reputation: 7664

jQuery: How to send $(this) as plugin parameter

I created a jQuery plugin that manage the input content (max chars, preg match,...). And I would like to use it like this:

$("form textarea.count-chars").smartInput({

    counterDiv: "#" + $(this).attr("id") + "-chars-left",
    maxChars: 128

});

This means, the plugin takes all the textareas with a class "count-chars" and display a countdown chars in a div block with the same id as the corresponding textarea + "-chars-left". And here the problem is...

console.log revealed that $(this).attr("id") refer to undefined !!!

So: How can I use the attributes of an input (for example) as a plugin parameter?

Here is the plugin: http://github.com/hassinus/smartInput

Thanks in advance.

Upvotes: 0

Views: 172

Answers (3)

nnnnnn
nnnnnn

Reputation: 150080

The reason $(this).attr("id") is undefined in the code you show is because at that point this has nothing to do with your jQuery "form textarea.count-chars" selector so this is not the "current" element being processed. $(this).attr("id") (along with the rest of that object literal) is evaluated first and the result is passed to your plugin.

If you need to retrieve some attribute for each matching element you need to do it inside your plugin. Or setup your plugin to take another parameter that is a callback function and then you can supply a function to somehow process the individual elements.

Following is a rough outline of how to do it:

(function( $ ) {
  $.fn.smartInput = function(options) {      
     this.each(function() {
        // get associated div's id via the supplied callback,
        // passing the current element to that callback            
        var associatedDivId = options.callback.call(this,this);

        // do something with the id
     });    
  };
})( jQuery );


$(("form textarea.count-chars").smartInput({
   maxChars : 128,
   callback : function(el) { return $(this).attr("id"); }
});

Upvotes: 0

Phil
Phil

Reputation: 165069

Only thing I can think of right now is to use .each()

$("form textarea.count-chars").each(function() {
    var ta = $(this);
    ta.smartInput({
        counterDiv: "#" + ta.attr("id") + "-chars-left",
        maxChars: 128
    });
});

Upvotes: 1

alex
alex

Reputation: 490667

You can't set this there.

Only in callbacks.

Upvotes: 1

Related Questions