0

I have some search fields on a page. Upon pressing 'enter' anything in these fields will then get filtered on for a dataset that's displayed on a table.

$("document").on('keyup', (e) => {
    if (e.keyCode === 13) {
        searchAndDraw();
    }
});

My issue is that I have a table #myTable with some textareas in tds . Hitting 'enter' inside a textarea also triggers the search as the table is inside the document.

How can I apply this keyup event to the doc but exclude #myTable?

I tried $("document:not(#tliId)").on('keyup'... but that does not work.

4
  • 2
    Why don't you give all the search fields a class, and bind the handler to that class? Commented Mar 9, 2022 at 21:59
  • 1
    It should be $("document :not(#tliId)") -- you need a space to match a descendant element. Commented Mar 9, 2022 at 21:59
  • 1
    well you should not be using an id selector if it is more than one element Commented Mar 9, 2022 at 22:13
  • 1
    Think you mean something like $(document).children(":not('#tliOd')").on("keyup", function(){}). You could also check the ID inside the callback. Commented Mar 9, 2022 at 23:22

1 Answer 1

2

You can target it to use enter on the inputs and exclude textarea

$(document).on('keyup', ":input:not(textarea)", (e) => {
  if (e.key === "Enter") {
    console.log("Enter");
  }
});
label {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label></label><input />
<label></label><textarea></textarea>
<label></label><textarea></textarea>
<label></label><input />

If you do not want the input to be in focus and they can hit enter anywhere you can check to see what the target is a textarea or not.

$(document).on('keyup', (e) => {
  if (e.key === "Enter" && !$(e.target).is('textarea')) {
    console.log("Enter");
  }
});
label {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label></label><input />
<label></label><textarea></textarea>
<label></label><textarea></textarea>
<label></label><input />

Sign up to request clarification or add additional context in comments.

Comments

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.