Reputation: 23
how can i prevent the user from further typing in the text-field once he/she has typed space character in the field? i tried following few lines of codes but it didn't work... any idea why???
HTML
<input id="username" type="text" onkeyup="abc(event);" />
Javascript
function abc(event){
for(i=0;i<document.getElementById("username").value.length;i++){
if(document.getElementById("username").value.charCodeAt(i) == 32){
event.preventDefault();
}
}
}
Upvotes: 2
Views: 89
Reputation: 9260
You should use
event.stopPropagation();
Your listener is a mess, try this instead:
function abc(event) {
if(event.keyCode === 32) {
console.log("space");
event.stopPropagation();
event.preventDefault();
}
}
You should also listen for either keypress
or keydown
.
Upvotes: 0
Reputation: 2125
You can prevent the use of space by adding this listener to your input.
function preventSpace(e) {
var char = e.which || e.charCode;
if(char == 32) {
e.preventDefault();
}
}
HTML
<input id="username" type="text" onkeypress="preventSpace(event);" />
Upvotes: 1