简体   繁体   中英

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 help!

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);
}

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();
});

function update() {
       $('#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM