how to press enter key programmatically in javascript

how to press enter key programmatically in javascript triggers 3 keyboard events keydown, keypress, or keyup. with Trigger Eneter key Press and Trigger Eneter + Shift key Press.

Free Live Chat for Any Issue

how to press enter key programmatically in javascript

triggers 3 keyboard events keydown, keypress, or keyup. The js trigger function example an event (for example a click, a key pressed…).

javascript key pressed enter

$('.container').on('keydown', 'input', function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
  	e.stopImmediatePropagation();
    //Do your business logic...
  }
});

don’t miss : Javascript Click Button By Id

Also Read This πŸ‘‰   Show country state city dropdown select box using javascript

HTML Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>how to press enter key programmatically in javascript - www.pakainfo.com</title>
</head>

<body>
    
    <div style="text-align: center;">
        <h2>Result</h2>
        <button>Trigger Enter Keypress</button>
    </div>

    <script src="main.js"></script>

</body>

</html>

Javascript Code – main.js
using document.document.body.dispatchEvent()

let btn = document.querySelector("button");
let result = document.querySelector("h2");

document.body.addEventListener("keydown", (e) => {
  if (e.key == "Enter") {
    result.innerText = "Enter Key Pressed";
  }

  if (e.key == "Enter" && e.shiftKey) {
    result.innerText = "Enter + Shift Key Pressed";
  }
});

btn.addEventListener("click", () => {
  
  const keyEvent = new KeyboardEvent("keydown", { key: "Enter"});
  
  // const keyEvent = new KeyboardEvent("keydown", { key: "Enter", shiftKey: true });

  document.body.dispatchEvent(keyEvent);
});

I hope you get an idea about how to press enter key programmatically in javascript.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.