Frank
Frank

Reputation: 624

jQuery $(this) selector within plugin call

I am currently integrating a jQuery plugin called RangeSlider JS.

This is the function in which I fire the plugin:

$('input[type="range"]').rangeslider({
    param: true, 
    param2: false,

    onInit: function() {    
        if ($(this).attr('name') === 'someName') {
            // do something ... 
        },
    }
});

Now, since I have more than one inputs of the type "range" that I am using the plugin for, I need to distinguish each input. I am trying to do this by getting the input's "name" attribute, but it seems like $(this) is not working from within that function.

Any ideas how to make the $(this) selector work? $(this) should refer to the input[type="range"].

Upvotes: 0

Views: 42

Answers (2)

Dave
Dave

Reputation: 10924

You can use jQuery.each() to iterate the results and store a reference to the current control.

$('input[type="range"]').each(function() {
  var that = $(this);
  that.rangeslider({
    param: true, 
    param2: false,
    onInit: function() {    
      if (that.attr('name') === 'someName') {
        // do something ... 
      },
    }
  });      
});

Upvotes: 1

jfriend00
jfriend00

Reputation: 707158

I had to look at the actual JS source code for that plugin to see how onInit() is called, but it looks like, this is set to a rangeslider Plugin object. And, this.$element will get you a jQuery object for the current element.

So, you should be able to do this:

$('input[type="range"]').rangeslider({
    param: true, 
    param2: false,

    onInit: function() {    
        if (this.$element.attr('name') === 'someName') {
            // do something ... 
        },
    }
});

Upvotes: 3

Related Questions