Javascript : How to get the last two characters typed into a textarea?

筅森魡賤 提交于 2019-12-01 05:38:55

问题


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!


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/5464084/javascript-how-to-get-the-last-two-characters-typed-into-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!