I did my homework and checked lots of questions but still couldn't find something that I can get to work.
I have a search input. When user clicks on example, I want the word "doctor" be written in my search input letter by letter. I could have done that by changing $("#search").val() long ago, but here is the problem. When normally user types into search input autocompletion div is coming out. It is triggered by keydown event. If i just change the val attribute of input, the autocomplete div won't come out, so I need to somehow trigger keydown event so it will come out.
I found this solution:
$("#example").click(function() {
$("#search").focus();
var e = jQuery.Event("keyup");
e.keyCode = 50;
$("#search").trigger(e);
});
but I couldnt get it to work. Any ideas please?
Here is how html looks:
<input type="text" id="search" />
Example: <span id="example">doctor</span>
HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box. The events related to keypresses are as follows : keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed.
The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event.
The keydown event occurs when a keyboard key is pressed down. The keydown() method triggers the keydown event, or attaches a function to run when a keydown event occurs.
jQuery | keypress() The keypress() method in jQuery triggers the keypress event whenever browser registers a keyboard input. So, Using keypress() method it can be detected if any key is pressed or not.
$("#example").click(function() {
$("#search").focus();
var e = jQuery.Event("keydown");
e.keyCode = 50;
$("#search").trigger(e);
});
ref: Definitive way to trigger keypress events with jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With