Veeru A S Veeru A S - 1 month ago 8
Javascript Question

Getting deleted character or text on pressing delete or backspace on a textbox

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

I have a key up event handler and i am capturing if the key is backspace. Now inside this I need to perform some tasks based on the key deleted. Please help.

Answer

After making a little tweak for the getCursorPosition function in this thread, you can get the characters deleted by tracking the current cursor selection.

The code handles the following conditions:

  1. Type and then backspace at the end.
  2. Move cursor in the middle of the text and delete/backspace.
  3. 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 Live Demo