Skip to content Skip to sidebar Skip to footer

How To Fire Keyboard Events In Javascript?

I'm giving a value to a textbox and then giving focus to it. document.getElementById('textbox').value='abcd'; document.getElementById('textbox').focus(); Then, I am creating a key

Solution 1:

You can't trigger browser keypress behavior with JavaScript simulated keypresses. You can only trigger your own function. What that means if that if you add a keypress event listener that checks if the a key is pressed and then does something, you can trigger that behavior, but you can't for example make the browser pull up it's "find" bar when you trigger ctrl+F. That would be a security issue.

The appropriate way would be to write your own function for selecting and fire it whenever you need it.

This should do what you're looking for: Live demo (click).

<input type="text" id="my-input" value="Some text.">

JavaScript:

var myInput = document.getElementById('my-input');

myInput.addEventListener('click', function() {
  this.focus();
  this.select();
});

var event = new Event('click');
myInput.dispatchEvent(event);

Post a Comment for "How To Fire Keyboard Events In Javascript?"