4

What I have to do is not permit to introduce number characters in a text input in a form, but I've to do it with javascript. Here's my HTML code:

<form id="formu">
<input type="text" id="num" />
</form>

And here's my JS code:

function numero(theEvent){

    var evento=theEvent||window.event;

        switch(evento.type){
            case 'keypress':
                if(document.getElementById("num").evento.keyCode>=48&&document.getElementById("num").evento.keyCode<=57){
                    return false;
                }
        }
    }
1
  • where did u call numero(theEvent) ? Commented Nov 15, 2013 at 9:14

4 Answers 4

9

You can use the new pattern attrib HTML ,

<input type="text" id="num" pattern="[A-Za-z]" title="Only Alphabets">
Sign up to request clarification or add additional context in comments.

Comments

3
function validateKeyStrokes(event) {
    var charCode = (event.which) ? event.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}


<form id="formu">
<input type="text" id="num"  onkeypress="return validateKeyStrokes(event)" />
</form>

Try this

Comments

0

Try using jQuery and a plugin for input text field filtering

See here

2 Comments

Why to use such a big library just to validate keystrokes?
It might be overkill indeed in some cases. On the other hand jQuery makes life easier with many common tasks which may justify using it. I've also thought about keypress event but it would not handle paste.
0

You can also use the HTML5 new input type number :

<input type="number" name="num" id="num">

But use with care if you want to provide old browsers support ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.