JavaScript keypress event get end value of textare

2019-04-24 17:47发布

I was wondering if it were possible to get the end result in the keypress event? Currently, I am using the keyup because it is activated after the user has done text editing in a texteara, but I have written a method that does something similar using the Mootools library:

input.addEvent("keypress", function (input) {
    var previous_result = this.value;
    var end_result = this.value + input.key;
});

However, this method is horrible when dealing with special keys such as backspace, or if the user chooses to use CTRL + a && Backspace in which case the value of the input element would not be "an empty string".

I'm curious because I have observed Google's search engine sending XMLHttpRequest AND mutating the page before the keyup event triggered. Additionally, the input they use manages to overcome my problem of removing entire text while still enjoying the luxury of keypress.

Thanks!

1条回答
何必那么认真
2楼-- · 2019-04-24 18:30

This will make it work:

input.addEvent( "keypress", function ( input ) {    
    setTimeout(function () {
        input.value // returns the updated value
    }, 0 );    
});

Live demo: http://jsfiddle.net/yQQ5P/ (I use built-in API, as I don't know Mootools)

So, you use a zero-timeout which acts as a yield. This gives the browser's UI thread an opportunity to updated the input's value.

查看更多
登录 后发表回答