0

I have an input field that needs to trigger event when press "Enter Key",

$(document).ready(function() {
  $(document).on('input', "#myInput", function(e) {
    console.log(e.KeyCode)
    if (e.KeyCode == 13) {
      console.log('Enter Key Pressed')
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="myInput" name="input_field">

But console.log(e.KeyCode) is always 'undefined'. Thanks

  • You cannot detect it with the _input_ event, you must use one of the _key*_ events instead – Phil Aug 05 '22 at 04:05
  • @Phil, I need it to trigger both on 'keyup' and 'keydown' that's why I use 'input' handler. But if I use both 'keydown' and 'keyup' handlers instead, it will tigger event twice at the same time. How can I handle that ? Thanks – user2273145 Aug 05 '22 at 04:09
  • Why do you need both key down and up? They're both separate events so it should not be surprising that the same handler would be triggered twice. – Phil Aug 05 '22 at 04:10
  • @Phil, it is a search box input that needs trigger event on key up and down. – user2273145 Aug 05 '22 at 04:14
  • That doesn't explain anything. Again, **why both**? You can't have `keyup` without `keydown` and it's pretty difficult to have `keydown` without a following `keyup` so why not just pick `keydown`? For any key event, that one is guaranteed to trigger – Phil Aug 05 '22 at 04:16
  • 1
    @Phil, I finally come to workaround this by separate the two events handler 'keypress' and 'input'; input handler for doing search job, and keypress for doing key press "Enter". Thanks – user2273145 Aug 05 '22 at 04:50

0 Answers0