-1

Hi I'm practicing JS and I have a question from javascript.

I'm gonna make the user to type only letters and if the user decides to type numbers too, the program stop him/her. and please no jQuery Answers cuz I don't know anything about it yet.

here's my code......

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function vent (t)
{
 var m=/^[a-zA-Z]+$/
  t=document.getElementById("txt");
 if(t.value.match(m))
 {
  alert("Co");
  return true;
 }
     
 else
 {
  // I want to write my preventing code here.......
 }
}
</script>
</head>
<body>
<input type="text" id="txt" onBlur="vent (this)"/><br/>
<input type="text"/>
</body>
</html>
MrCode
  • 63,975
  • 10
  • 90
  • 112
Bernard
  • 3
  • 2
  • 1
    possible duplicate of [Check if input is number or letter javascript](http://stackoverflow.com/questions/18042133/check-if-input-is-number-or-letter-javascript) – Stephen Ó Connor May 16 '15 at 15:41
  • Try this: http://stackoverflow.com/questions/23556533/how-do-i-make-an-input-field-accept-only-letters-in-javascript Thanks – Ganesh Uppinivalasa May 16 '15 at 15:47

1 Answers1

0

When restricting user input to a subset of key values you would typically use the onkeydown event rather than blur. That way you can prevent the user's keystroke from being added to the input value rather than trying to remove it after the fact. All you need to do is cancel the event, using preventDefault() or returning false from the keydown handler. Note for older browsers you may need to check for keyCode in addition to which, i.e., var c = e.which || e.keyCode; then check the value of c against the allowed range.

function allowOnlyCharacters(e)
{
    return e.which == 16 || (e.which >= 65 && e.which <= 90);
}

var element = document.getElementById('txt');
element.onkeydown = allowOnlyCharacters;
<input type="text" id="txt"/><br/>
<input type="text"/>
tvanfosson
  • 524,688
  • 99
  • 697
  • 795