Legionar
Legionar

Reputation: 7607

How can I trigger only the first function inside second function

I have many elements, where some of them has two classes, and some only one.

Shorten code:

<input type="text" class="first second" value="" />
<input type="text" class="second" value="" />
<input type="text" class="first" value="" />
<input type="text" class="second" value="" />
<input type="text" class="first second" value="" />
<input type="text" class="first second" value="" />

jQuery:

var my_function = function() {
  // ...
};

$('.first').on('change', my_function);

$('.second').on('change', function() {
  // ...
  // here I want to trigger the above onchange function for the same element with class "first"
  // but "$(this).trigger('change');" will call both

  if (some_condition) {
    my_function(this); // <== here I get error "g.nodeName is undefined" in jQuery library
  }
});

How can I trigger only the first function inside of the second function?

Upvotes: 1

Views: 72

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

Try to use a function:

function f(obj) {
//stuf here
}
$('.first').on('change', function() {
  f($(this));
});

$('.second').on('change', function() {
  // ...other stuf here
 f($(this));
});

or use namespaces:

$('.first').on('change.first', function() {
  // ...
});

$('.second').on('change.second', function() {
  // ...
  // here I want to trigger the above onchange function for the same element with class "first"
  $(this).trigger('change.first');
});

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 241138

If you want to invoke the function with the same context, use the .call() method:

var my_function = function() {
  // ...
}

$('.first').on('change', my_function);

$('.second').on('change', function() {

  if (some_condition) {
    my_function.call(this);
  }
});

Upvotes: 1

Related Questions