Getting the character or text to be deleted by clicking delete or backspace in the text box

I have a text box, I want to get the deleted character when I press the backspace or delete key.

I have a key up event handler and I grab if the key is backspace. Now inside this I need to perform some tasks based on remote keys. Please, help.

+4
source share
3 answers

By making a small tweak to the getCursorPosition function in this thread , you can get characters deleted by tracking the current cursor selection.

The code processes the following conditions:

  • Type and then back to the end.
  • Move the cursor in the middle of the text and delete / return.
  • Select a piece of text and then delete / backspace.
 $.fn.getCursorPosition = function() { var el = $(this).get(0); var pos = 0; var posEnd = 0; if('selectionStart' in el) { pos = el.selectionStart; posEnd = el.selectionEnd; } else if('selection' in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; posEnd = Sel.text.length; } // return both selection start and end; return [pos, posEnd]; }; $('#text').keydown(function (e) { var position = $(this).getCursorPosition(); var deleted = ''; var val = $(this).val(); if (e.which == 8) { if (position[0] == position[1]) { if (position[0] == 0) deleted = ''; else deleted = val.substr(position[0] - 1, 1); } else { deleted = val.substring(position[0], position[1]); } } else if (e.which == 46) { var val = $(this).val(); if (position[0] == position[1]) { if (position[0] === val.length) deleted = ''; else deleted = val.substr(position[0], 1); } else { deleted = val.substring(position[0], position[1]); } } // Now you can test the deleted character(s) here }); 

And here is the Live Demo

+5
source

Instead, you can use the keydown event handler so that the last character to be deleted is still available:

 $('textarea').on('keydown',function(e) { var deleteKeyCode = 8, value = $(this).val(), length = value.length, lastChar = value.substring(length-1, length); if (e.which === deleteKeyCode) { alert(lastChar); } }); 
+3
source

Live demo

 $('input').keydown(function(e){ $(this).data('prevVal', $(this).val()); }).keyup(function(e){ if(e.keyCode === 8) {//delete var ele = $(this); var val = ele.data('prevVal'); var newVal = ele.val(); var removedChar = val.substring(val.length-1); alert(removedChar); } }); 
-1
source

Source: https://habr.com/ru/post/1485243/


All Articles