3

I am trying to implement a command line emulator in JavaScript. I want the Spacebar key to act as Enter (submit, then clear the command line).

In this post, let's represent a space as an underscore, so _ means [space]:

If I enter banana_ and then, after catching the keypress, I call input.value= "", it clears banana, but not the remaining space.

I tested both onkeydown and onkeypress, but it doesn't seem to make any difference. Actually, onkeyup does the trick, see my answer below!

This is my code. Could someone please help me remove the extra space...

<html><head>

<script type="text/javascript">  

    document.onkeypress = keyCheck;  

    function keyCheck( e ) {  
        var keyID = (window.event) ? event.keyCode : ( e.keyCode ? e.keyCode : e.charCode );  
        switch(keyID) {  
            case 32: //spacebar  
                alert( "space pressed, clearing..." );  
                document.getElementById( "cli" ).value="";  
                break;  
            default:  
                //do something else  
                break;  
            } 
        }  
</script>  
</head>  

<body>
  <form name="frm" id="frm" onSubmit="go( this )">
  <input name="cli" id="cli" type="text" name="cmd" size="122">
</body>

</html>
wattostudios
  • 8,666
  • 13
  • 43
  • 57
Hans
  • 158
  • 5

1 Answers1

2

Use onkeyup instead.

document.onkeyup = keyCheck;

This way the event occurs after the character has been added to the value of the element.

Try it out: http://jsbin.com/esacu3

user113716
  • 318,772
  • 63
  • 451
  • 440
  • Excellent! Many thanks. I'm sorry, I thought I already tested this, turns out I didn't or something. Is there a reason why "onkeypress" doesn't clear the space, but "onkeyup" does? (I thought 'onkeypress' waited both for "onkeyup" and "onkeydown" to finish). – Hans Nov 08 '10 at 16:08
  • 1
    @Hans - Because the `onkeypress` event fires *before* the character gets added to the input, so the sequence goes *handler fires > value is cleared > character is added*. With `onkeyup`, the handler fires *after* the character is added to the value, so *character is added > handler fires > value is cleared*. What makes `onkeypress` different from `onkeydown` is that it continuously fires if you hold down a key. – user113716 Nov 08 '10 at 16:15