jquery - Javascript : How to get the last two characters typed into a textarea? - Stack Overflow

What is the best way to grab the last two characters typed into a textarea box?I need the last 2 charac

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!

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!

Share Improve this question asked Mar 28, 2011 at 19:33 wilsonpagewilsonpage 17.6k23 gold badges105 silver badges150 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

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/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 ment to my answer for an explanation of what filtering should take place. My initial note was mistaken, based on a quick test in Chrome.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744289816a4566979.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信