Skip to content Skip to sidebar Skip to footer

Javascript : How To Get The Last Two Characters Typed Into A Textarea?

What is the best way to grab the last two characters typed into a textarea box? I need the last 2 characters typed NOT the last two characters of the overall string. Appreciate the

Solution 1:

You need to catch the keypress event on the textarea and then keep a log of keys that were pressed. Note that this is going to catch arrow keys, shift, alt, etc so if you just want characters you need to filter them out.

Simple example:

var keyPresses = [];
textarea.onkeypress = function(ev){
   ev = ev || window.event;

   var key = ev.keyCode || ev.which;
   keyPresses.push(key);
}

Solution 2:

Here's a demo of doing it with jQuery, while displaying the last two characters that were entered: http://jsfiddle.net/Ender/5gUHb/

And the source:

var keys = [];
$('#target').keypress(function(e) {
    keys.unshift(e.which);
    update();
});

functionupdate() {
       $('#last')
           .prepend($('<li/>').text(String.fromCharCode(keys[0])))
           .children(':eq(2)').remove();
}

This demo captures the keypress event on the text area, unshifts the value onto the array (because then the indexes are representative of the number of keys that have been pressed since that key was pressed) and then updates the display.

The display update simply pushes the first value from the array to the top of a <ul> and removes the child (if any) at index 2 in the list.

Note additionally that because of the way jQuery deals with .keypress(), you do NOT have to filter out modifier or arrow keys.

UPDATE Please see Tim Down's comment to my answer for an explanation of what filtering should take place. My initial note was mistaken, based on a quick test in Chrome.

Post a Comment for "Javascript : How To Get The Last Two Characters Typed Into A Textarea?"