Home > OS >  How to press the enter-key inside an input field with pure JavaScript or jQuery?
How to press the enter-key inside an input field with pure JavaScript or jQuery?

Time:02-15

i want to simulate an enter-press inside a text-input-field that i can identify using an id. First i will find my textfield by document.getElementById. This works pretty fine. Next, i want to click inside the textfield so set the cursor inside it. And last i want to press enter. I have no idea how i can do this. And I couldn't find any solution here.

My code looks a follow:

let plzField = document.getElementById("filter"); //find the text-field (works)
plzField.click(); // works
plzField.enter(); // does not work

Please help!

CodePudding user response:

As per your question, it seems, that you want to detect on enter event occurred or not. In pure Javascript, there is no such onenter event, but with eventCode or eventName you can check that.

You need to apply filter as you applied in you code and then you need to check for keyPress() event and within this event you need to check `event.code || event.key' like below

document.getElementById('foo').onkeypress = function(e){
    if (!e) e = window.event;
     var keyCode = e.code || e.key;
    if (keyCode == 'Enter'){
      // Enter pressed
      alert(this.value);
     }
  }
<input type="text" id="foo" />

CodePudding user response:

$("#id_of_textbox").keyup(function(event) {
  if (event.keyCode === 13) {
    $("#id_of_button").click();
  }
});

$("#pw").keyup(function(event) {
  if (event.keyCode === 13) {
    $("#myButton").click();
  }
});

$("#myButton").click(function() {
  alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br> Password:&nbsp;
<input id="pw" type="password"><br>
<button id="myButton">Submit</button>

  • Related