Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger keypress(keydown) with jQuery

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>
like image 860
Nazar Avatar asked Sep 15 '11 07:09

Nazar


People also ask

How do I trigger Keydown event?

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.

How do you trigger a Keyup event?

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.

What is Keydown event in jQuery?

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.

How does jQuery detect keyboard press?

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.


1 Answers

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

like image 197
Rafay Avatar answered Nov 06 '22 03:11

Rafay