admin管理员组

文章数量:1193317

I'm trying to trigger an enter keypress event on my input without actually pressing the enter key, more just onload.

I found out that initKeyboardEvent and initKeyEvent are both deprecated even e.keyCode and e.which are being removed from web standards.

I also found this post that goes over how to do this in jQuery. However, I've been trying to figure out how to do this in vanilla JS and no luck.

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.keyCode == 13) {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyboardEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
<input type="text" id="txtbox" placeholder="trigger enter key press">

I'm trying to trigger an enter keypress event on my input without actually pressing the enter key, more just onload.

I found out that initKeyboardEvent and initKeyEvent are both deprecated even e.keyCode and e.which are being removed from web standards.

I also found this post that goes over how to do this in jQuery. However, I've been trying to figure out how to do this in vanilla JS and no luck.

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.keyCode == 13) {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyboardEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
<input type="text" id="txtbox" placeholder="trigger enter key press">

Share Improve this question edited Aug 15, 2018 at 10:43 halfer 20.4k19 gold badges108 silver badges201 bronze badges asked Aug 9, 2018 at 20:27 Michael SchwartzMichael Schwartz 8,41514 gold badges88 silver badges153 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 27

Since initKeyboardEvent is deprecated use constructor instead: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key is not deprecated so we can use key === "Enter"

Also trigger enter on txtbox instead of body

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.key == "Enter") {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = new KeyboardEvent('keydown', {altKey:false,
  bubbles: true,
  cancelBubble: false, 
  cancelable: true,
  charCode: 0,
  code: "Enter",
  composed: true,
  ctrlKey: false,
  currentTarget: null,
  defaultPrevented: true,
  detail: 0,
  eventPhase: 0,
  isComposing: false,
  isTrusted: true,
  key: "Enter",
  keyCode: 13,
  location: 0,
  metaKey: false,
  repeat: false,
  returnValue: false,
  shiftKey: false,
  type: "keydown",
  which: 13});

txtbox.dispatchEvent(ev);

本文标签: javascriptTrigger Enter keypress in vanilla JSStack Overflow