Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript keypress event get end value of textarea

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.

like image 953
User2121315 Avatar asked Feb 12 '13 21:02

User2121315


1 Answers

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.

like image 181
Šime Vidas Avatar answered Nov 08 '22 18:11

Šime Vidas