4

I have several html input controls on a page and a search button. When user is outside the input controls, ( ie focus is not inside the input control) and if user press enter, i want to trigger click event of search button. The search button is not a Submit button and it is not inside a form

<input type="text" id="input1" />
<input type="checkbox" id="input2" />
<input type="text" class="autocomplete" id="input3" />

<button type="button" id="btnSearch">Search</button>

currently I am doing this

$(document).keypress(function (event) {
    if (event.keyCode === 13) {
        $("#btnSearch").click();
    }
})

However, the above code triggers click event every time user clicks enter.

Some of the input controls I have are custom autocomplete controls. Auto complete control shows multiple options as soon user starts typing something. Then user can select the option by using mouse or by pressing enter.

I don't want to trigger the click event of a search button when user press enter to select an option.

LP13
  • 30,567
  • 53
  • 217
  • 400

1 Answers1

3

Just make sure that the autocomplete element isn't the source of the enter press. From the demo you give in your question, this will work. However, if it is slightly different in your use case, you may need to adjust the class name or selector to make sure it is preventing the correct target element

$(document).keypress(function (event) {
       if (event.keyCode === 13 && !$(event.target).hasClass("autocomplete")) {
           $("#btnSearch").click();
           alert('btnSearchClick');
       }
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" />
<input type="checkbox" id="input2" />
<input type="text" class="autocomplete" id="input3" />

<button type="button" id="btnSearch">Search</button>

Alternatively, since events propagate out, if you can prevent the propagation of the autocomplete event in whichever library you are using, that may work as well.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • is `event.target` available in all the browsers? – LP13 Apr 02 '18 at 21:16
  • @LP13 - Yes: https://developer.mozilla.org/en-US/docs/Web/API/Event/target However, if you must support IE6-8 then it would be required to use `.srcElement` instead of `.targetElement` (as noted in the link as well). – Travis J Apr 02 '18 at 21:18
  • Should i use `event.which` or `event.keyCode` https://api.jquery.com/event.which/ – LP13 Apr 03 '18 at 18:42
  • @LP13 - I personally use `keyCode` so it didn't seem out of place to me when you used it here. I would stick with `keyCode`. Here is some more info on it: https://stackoverflow.com/a/4471635/1026459 – Travis J Apr 03 '18 at 18:47