-1

Possible Duplicate:
jQuery Event Keypress: Which key was pressed?

I'm using below code to fire an alert every time a new space char is encountered as a user types into a text box. This works until the user enters the first space, as the alert will be fired for each subsequent space.

For this String : 'test ' the alert will be fired once, which is correct

For this String : 'test test' the alert will be fired 5 times, but it should be just fired once.

For this String : 'test test test' the alert should be fired three times.

How can below code be amended so that alert fires just once for each new space character ?

$("#myDiv").keyup(function() {    
    if$("#myDiv").val().indexOf(' ') != -1)
    {
        alert("space found");
    }   ​
};
Community
  • 1
  • 1
blue-sky
  • 51,962
  • 152
  • 427
  • 752

3 Answers3

4

Pass the event object to the callback function, and test e.which == 32 for keycode 32 (space)

// keyup callback receives the Event object e
$("#myDiv").keyup(function(e) {
    // When the key pressed was space, alert...
    if (e.which == 32)  {
        alert("space found");
    }   
});​

http://jsfiddle.net/DL5pX/

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
1

How about:

$("#myDiv").keyup(function() {

    var val = $(this).val(),
        len = val.length - 1;

    if (val[ len ] == ' ') {
        alert("space found");
    }

});

jsFiddle Demo

David G
  • 94,763
  • 41
  • 167
  • 253
0

You could do this by following code,

var x = false;
$(function() {
  $(document).keyup(function(e) {
    if (e.keyCode == 32) {
      x = false;
    }
  }).keydown(function(e) {
    if (e.keyCode == 32) {
      x = true;
      alert('space pressed!!');
    }
  });
}
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
Darknight
  • 1,132
  • 2
  • 13
  • 31