Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery plugin doesn't work when called twice

I know this a problem with the way I have coded the plugin for dealing with multiple instances. I'm pretty sure at least one of my variables is being overwritten by each subsequent call of the plugin. Anyway, here's the plugin code:

$.fn.extend({
dependsOn: function( $claimer ){
    $dependent = $(this);
    $claimer.change(function(){
        alert( $dependent.attr('id') );
        var $selected = $('option:selected', this);
        var pk = $selected.attr('class');

        $dependent.removeAttr('disabled');
        $dependent.find('option').each(function(){
            $hiddenOpts = $dependent.parent().find('.hiddenOptions');
            $hiddenOpts.append( $(this) );
            $hiddenOpts.find('option').each(function(){
                if( $(this).attr('ref') == pk || $(this).hasClass('empty') )
                    $dependent.append( $(this) );
            });
        });
    });
}
});

When I call $('.something').dependsOn( $('.somethingElse') );, it works fine, but if I call it again on two other items, the $dependent variable gets set to THAT element.

The point of the plugin is to keep select boxes disabled until a previous select box is changed. If I have three select boxes in a row, and I want the first one enabled, the second one dependent on the first, and the third dependent on the second, I'd call $(second).dependsOn( $(first) ), and $(third).dependsOn( $(second) ), so changing the first would then enable the second but not the third, and changing the second would then enable the third.

But with the current code, changing the first enables the third, but not the second (like I said, I think it's because $dependent is being overwritten and set to the third thing after calling dependsOn twice).

If that's not clear, let me know.

like image 629
Jake Avatar asked Jan 26 '12 03:01

Jake


2 Answers

That's because you're not defining a new variable in the scope of dependsOf (which is done using var $dependent = blah). Instead, you're setting the value of $(this) to a global version of $dependent.

That's the reason why it's being replaced.

Good luck :)

like image 127
Gonzalo Larralde Avatar answered Sep 30 '22 15:09

Gonzalo Larralde


The way you're declaring $dependant is making it a global variable, so the next time the function is called it sets the same global $dependant to the new value. Try:

var $dependant = $(this);

like image 33
Daniel Mendel Avatar answered Sep 30 '22 15:09

Daniel Mendel