Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get textarea value once a key pressed

I have an function executed after a keypress event :

$("#txtarea").keypress(function(){
    alert(document.getElementById("txtarea").value);
});

I want to return the new text of the textarea after every keypress, so that it can be used simultanuously in other javascript functions.

The problem with this script is that once a key is pressed, the function displays "" empty string.

Thank you in advance.

like image 544
SmootQ Avatar asked Nov 01 '25 10:11

SmootQ


2 Answers

Try to use keyup instead of keypress

like image 128
antyrat Avatar answered Nov 04 '25 00:11

antyrat


The keypress just get fired before the value assigned. Like every other event(click, submit etc'...) so you can cancel the default behavior and "stuff"

$('#txtarea').keypress(function(event) {
    return false; // this will disable the new value assignment
});

You can find out what button was clicked with event.which and work with it.

Example:

<input id="txtarea" />​

$('#txtarea').keypress(function(e){
    var value = this.value; 
    alert(value);
    alert(value + String.fromCharCode(e.which))
})​;

JSFiddle DEMO

You can also use the keyup event, but it has other meaning and usage than keypress.
Be aware!

like image 23
gdoron is supporting Monica Avatar answered Nov 03 '25 23:11

gdoron is supporting Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!