Getting Deleted character

The following will work in all major browsers for text <input> elements. It shouldn't be used for <textarea> elements because the getInputSelection function doesn't account for line breaks correctly in IE. See this answer for a (longer) function that will do this.

function getInputSelection(input) {
    var start = 0, end = 0;
    input.focus();
    if (    typeof input.selectionStart == "number" &&
            typeof input.selectionEnd == "number") {

        start = input.selectionStart;
        end = input.selectionEnd;
    } else if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        if (range) {
            var inputRange = input.createTextRange();
            var workingRange = inputRange.duplicate();
            var bookmark = range.getBookmark();
            inputRange.moveToBookmark(bookmark);
            workingRange.setEndPoint("EndToEnd", inputRange);
            end = workingRange.text.length;
            workingRange.setEndPoint("EndToStart", inputRange);
            start = workingRange.text.length;
        }
    }
    return {
        start: start,
        end: end,
        length: end - start
    };
}

document.getElementById("aTextBox").onkeydown = function(evt) {
    evt = evt || window.event;
    var keyCode = evt.keyCode;
    var deleteKey = (keyCode == 46), backspaceKey = (keyCode == 8);
    var sel, deletedText, val;
    if (deleteKey || backspaceKey) {
        val = this.value;
        sel = getInputSelection(this);
        if (sel.length) {
            deletedText = val.slice(sel.start, sel.end);
        } else {
            deletedText = val.charAt(deleteKey ? sel.start : sel.start - 1);
        }
        alert("About to be deleted: " + deletedText);
    }
};

Assuming the input box has an id 'input'. Here is how with least amount of code you can find out the last character from the input box.

document.getElementById("input").onkeydown = function(evt) {
  const t = evt.target;
  if (evt.keyCode === 8) { // for backspace key
    console.log(t.value[t.selectionStart - 1]);
  } else if (evt.keyCode === 46) { // for delete key
    console.log(t.value[t.selectionStart]);
  }
};
<input id="input" />

No, there is no variable that stores the deleted char. Unless you have a history for Undo/Redo, but it would be difficult to get the information out of that component.

Easiest would be to compare the contents of the input field before and after delete/backspace have been pressed.

Tags:

Javascript