Bruno Crosier
Bruno Crosier

Reputation: 758

Dispatch / generate keydown event in Vanilla JS (no jQuery, use Vanilla JS)

How can I simulate a keypress to an input, using vanilla javascript?

I have tested every possible answer on SO and elsewhere, and it doesn't work on Chrome or Firefox.

For example, let's say we have a form:

<input id="myInput" type="text">
<button id="myButton>Click Me</button>

How could I make it so that when the button is clicked, the letter "a" is added to the input?

Upvotes: 2

Views: 1556

Answers (2)

Manu Sampablo
Manu Sampablo

Reputation: 350

This way works i think:

<html>
<body>

<input type="text" id="myText" placeholder=" ">

<button id="but1" onclick="myFunctionA()">A</button>
<button id="but2" onclick="myFunctionB()">B</button>

<script>
  function myFunctionA() {
  document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "A";
}

function myFunctionB() {
  document.getElementById("myText").placeholder = document.getElementById("myText").placeholder + "B";
}

//And so on 

</script>

</body>
</html>

Any doubts tell me

Upvotes: 0

Carl Edwards
Carl Edwards

Reputation: 14424

You'd first add a keyup event listener to the document object and inside the callback you assign the value of the input via value depending on which key was pressed:

var input = document.getElementById("myInput");

document.addEventListener('keyup', function(e) {
  if (e.which === 39 || e.which === 19) {
    input.value += 'a';
  }
});
<input id="myInput" type="text" />

<button id="myButton">Click Me</button>

Upvotes: 3

Related Questions