Home > OS >  jquery document with not selector
jquery document with not selector

Time:03-11

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.

CodePudding user response:

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 />

  • Related