cgcgbcbc
cgcgbcbc

Reputation: 549

jQuery trigger keyup on input gets old value

I try to manually trigger key-up event in qunit test but it fails since manually trigger key-up event will not change the input value.

http://jsfiddle.net/Re9bj/4/

$('input').on('keyup', function (event) {
    $('div').html($('input').val());
});

var e = $.Event('keyup', {
    keycode: 68
});
$('input').trigger(e); //this trigger will not change the input value

This trigger will work but the problem is that input value never change.

Upvotes: 0

Views: 2222

Answers (1)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33880

You can't add a character with a simple trigger. Trigger will only fire events, but not the default behavior. You need to simulate it.

To do that, you can use this code :

if(event.isTrigger && event.keycode) this.value +=  String.fromCharCode(event.keycode);

It will check if the event is triggered and then print the value.

Final code :

$('input').on('keyup', function (event) {
    if(event.isTrigger && event.keycode) this.value +=  String.fromCharCode(event.keycode);
    $('div').html($('input').val());
});

var e = $.Event('keyup', {
    keycode: 68
});
$('input').trigger(e);

Fiddle : http://jsfiddle.net/Re9bj/9/

Upvotes: 4

Related Questions