Set form input value to “” doesn't clear spaces
-
29-09-2019 - |
Question
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>
Solution
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow