Collins
Collins

Reputation: 1149

jQuery this inside this

I have the following jQuery which isnt working, and I think the answer may because I am using "this" inside "this".

  $('.field-name-field-choose-a-service input:checked').each(function() {
    var unitname = $(this).closest('.form-item').text();
    $('.field-name-field-choose-a-package .form-type-checkbox').each(function() {

      if($(this).children('.views-field-field-bookable-unit-type span').text() == unitname) {
        $(this).show();

      } 
    });

  });

How do I get "this" to only apply to whats happening in the current function?

Sorry if this isnt detailed enough, im a bit of a newbie to jQuery!

Upvotes: 0

Views: 3383

Answers (2)

frank91
frank91

Reputation: 131

Try storing $(this) element in a variable and then using variable instead of using $(this)

Upvotes: 0

David
David

Reputation: 218877

When you're inside the context of another .each(), the meaning of "this" changes therein. If you need a reference to the "outer this", capture it in a variable:

$('.field-name-field-choose-a-service input:checked').each(function() {
    var outerThis = this;
    var unitname = $(this).closest('.form-item').text();
    $('.field-name-field-choose-a-package .form-type-checkbox').each(function() {
        // "this" refers to the "inner this"
        // "outerThis" refers to the "outer this"
    });
});

});

Upvotes: 4

Related Questions