How to detect that a space has been replaced or deleted

I need to find a way to determine if the space has been removed or backspaced, and run the function, if so. I am working on this in JavaScript / jQuery.

I know that I can get the Delete or Back key pressed using:

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

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

Very grateful for any suggestions.

+6
source share
4 answers

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 keeps track of the current number of whitespace in the input, and if this number ever decreases, it warns (or does whatever you want).

+2
source

Bind to keydown and compare the value from before and after to see if it has decreased.

 $(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 example:

 $("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/

+2
source

Download the value in advance (set the value by pressing the key) and compare it with the value after pressing the key. This is the only way to know with certainty that one or more spaces have been removed. Any key verification depends on how you can determine which possible keys can achieve the removal of space, and are likely to leave holes.

As an example, selecting the final letter of a word and the space after it, if we press the last letter, it will remove the space. But a keystroke is not reverse or remote.

+2
source

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); } } }); 
+1
source

All Articles