1

I have the following line of jquery which reacts to any key up event in any text input on a form. It then runs a function called processPrimarySearch:

$('#primarySearch input[type="text"]').on('keyup', this, processPrimarySearch);

This works, but I want to adapt it so keyup ignores a tab key press as described here: Keyup event behavior on tab

I can't work out how to re-write this as I don't understand how to pass this before calling processPrimarySearch. For example I have the following but it doesn't work and I don't understand what I'm supposed to write to make it work:

$('#primarySearch input[type="text"]').on({

    "keyup": function(e) {
        if (e.which != 9) {
            // No reference to 'this'!
            processPrimarySearch();
        }
    }
});

function processPrimarySearch() {
    // ...
}
Andy
  • 5,142
  • 11
  • 58
  • 131

1 Answers1

3

Your logic is almost correct, you just need to use call() to provide the context for the function. Try this:

$('#primarySearch input[type="text"]').on({
  "keyup": function(e) {
    if (e.which != 9) {
      processPrimarySearch.call(this);
    }
  }
});

function processPrimarySearch() {
  // ...
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Works perfectly. Thank you so much. I wasn't aware of `.call()` so will look further into this. – Andy Jun 29 '17 at 09:27
  • No problem, glad to help. Here's the docs for your reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call – Rory McCrossan Jun 29 '17 at 09:28