0

I have got an Input field which I want to execute. Normally I would do it by document.getElementById("myinput").click(), but it is an Input so I have to execute it by simulating enter.

I want something like document.getElementById("myinput").performEnter();

I found this from How to trigger the enter keypress:

var e = $.Event( "keypress", { which: 13 } );
$('#yourInput').trigger(e);

but is there a way to do this only in JavaScript?

Community
  • 1
  • 1
Erdnuss
  • 307
  • 4
  • 16

1 Answers1

1

You can create a custom event and use that with JQuery's .trigger() method.

var $txt = $("#txt");
var $btn = $("button");

$txt.on("keydown", function(evt){
  if(evt.keyCode === 13){
      // Create a custom event and pass to the button
      var e = $.Event("keydown");
      e.which = 13;   // ENTER
      e.keyCode = 13;
      $btn.trigger(e);  // Trigger the event for the button
  }
});

// Here is the code for a test button
$btn.on("keydown", function(evt){
  if(evt.keyCode === 13){
    console.log("You pressed ENTER in the text box and triggered the keydown event with ENTER!");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt">

<button>Test Button</button>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71