Question

I need to find a way to detect if a space was deleted or backspaced, and run a function if that is the case. I am working on this in JavaScript / jQuery.

I know I can get the delete or backspace key press by using:

$(this).keyup(function(event) {
        event.keyCode

However, I do not know how to tell if the delete or backspace command removed a space?

Very appreciative for any suggestions.

Was it helpful?

Solution

See here: http://jsfiddle.net/Txseh/

(function(){
    var currentWhitespaceCount;

    $("input").keyup(function(e){
        var newCount = ($(this).val().match(/\s/g) || []).length;

        if (newCount < currentWhitespaceCount)
            alert("You removed one or more spaces, fool.");

        currentWhitespaceCount = newCount;
    });
})();​

It tracks the current number of whitespace characters in the input, and if ever the number goes down, it alerts(or does whatever you want).

OTHER TIPS

Cache the value beforehand (set a value on keypress) and compare with the value after keypress. That is the only way to know with certainty that one or more spaces has been removed. Any checking of keys relies on you being able to work out what possible keys could achieve the removal of a space, and will likely leave holes.

As an example, selecting the final letter of a word and the space following it, if we press the last letter it will remove the space. But the key pressed is not backspace or delete.

Bind to the keydown and compare the value from before and after to see if it reduced in size.

$(input).keydown(function(){
    var currVal = this.value, self = this;
    setTimeout(function(){
        if ( currVal.length > self.value.length ) {
            console.log(currVal.length - self.value.length + " characters have been removed.");
        }
    },0);
});

http://jsfiddle.net/ymhjA/1/

Updated sample:

$("input").keydown(function() {
    var currVal = this.value,
        self = this;
    setTimeout(function() {
        if (currVal.length - self.value.length === 1) {
            var origVal = $.grep(currVal.split(""),function(val){
                return val === " ";
            });
            var newVal = $.grep(self.value.split(""),function(val){
                return val === " ";
            });
            if ( origVal.length != newVal.length ) {
                console.log("a space was removed");
            }
        }
    }, 0);
});​

http://jsfiddle.net/ymhjA/4/

actually here is my code http://jsbin.com/atuwez/3/edit

 var input = $('#input'),
     afterLength,
     beforeLength;

input.on({
  'keydown': function () {
    beforeLength = input.val().split(/\s/).length;
  },
  'keyup': function(event) {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 ) {
          afterLength = input.val().split(/\s/).length;
          console.log(beforeLength == afterLength);
    }
  }

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top