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() {
    // ...
}
0

1 Answer 1

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() {
  // ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Works perfectly. Thank you so much. I wasn't aware of .call() so will look further into this.
No problem, glad to help. Here's the docs for your reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.