Masiar
Masiar

Reputation: 21352

JQuery simulating keypress event on an input field

I have an input field which is dynamically filled with some AJAX, and once it's filled I would like to have JavaScript to automatically press "Enter" (key event 13) on that input inducing another function, which is hidden to me, to trigger.

Would it be possible with jQuery? I have this code right now, which is not working:

$('#myInputId').focus().trigger({ type : 'keypress', which : 13 });

Do you have any clue on what am I doing wrong?

Upvotes: 24

Views: 65005

Answers (4)

Ameer
Ameer

Reputation: 433

This method worked for me.

    var keyEvent = jQuery.Event("keypress");
    keyEvent.keyCode = 13;
    $("#myInputId").trigger(keyEvent);

Upvotes: 0

Masoud Darvishian
Masoud Darvishian

Reputation: 3964

On Keypress Enter :

$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in somewhere');   
    }
});

Upvotes: -2

Felix Kling
Felix Kling

Reputation: 816282

You can create an event object:

$('#myInputId').trigger(jQuery.Event('keypress', { keycode: 13 }));

Upvotes: 37

John
John

Reputation: 1319

Hi you could try use the change event for when the input area changes :

$('#myInputId').change(function(){
    $('#myInputId').focus().trigger({ type : 'keypress', which : 13 });


});

Upvotes: 3

Related Questions