[removed] How to get the last two characters typed into a textarea?

后端 未结 2 1454
误落风尘
误落风尘 2021-01-14 15:16

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 th

2条回答
  •  渐次进展
    2021-01-14 15:41

    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($('
  • ').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

      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.

提交回复
热议问题