Lukas Glaser
Lukas Glaser

Reputation: 27

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

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!

Upvotes: 1

Views: 9511

Answers (3)

Sahil Thummar
Sahil Thummar

Reputation: 2490

Use Keyup Event Listener. keycode for enter is 13.

For More Example, Please visit https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter

let plzField = document.getElementById("filter");

plzField.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
    console.log(event.target.value);
  }
});
<input type="text" id="filter" />

Upvotes: 6

Mohammed
Mohammed

Reputation: 658

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

var textInput = document.getElementById('foo');
function enter() {
    var keyboardEvent = new KeyboardEvent('keydown', {
        code: 'Enter',
        key: 'Enter',
        charKode: 13,
        keyCode: 13,
        view: window
    });

    textInput.dispatchEvent(keyboardEvent);
}

textInput.addEventListener('keydown', function (e) {
    console.log(e);
});
enter()
<input type="text" id="foo" />

Upvotes: 3

Ivan Kuznetsov
Ivan Kuznetsov

Reputation: 1

$("#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>

Upvotes: -1

Related Questions