tags:

views:

74

answers:

4

what is the code if you want that only number should be inputted in an html textbox. If you input letters there will be no letter that would show. If you input numbers, the numbers would show, please help

+2  A: 

You will need to use JavaScript to control this, I recommend using jQuery and this is one of many input masking plugins: http://digitalbush.com/projects/masked-input-plugin/

Dustin Laine
A: 

The text attribute is available for html forms. I suggest you use a regex on the server side to have it just return a number. You may be able to use a regex with javascript but that might not be as secure as a server side implementation.

Jonno_FTW
It's a value for the type attribute, not an attribute in its own right. Regular expressions shouldn't be the instant go to — there are often more efficient and easier to read methods for determining if something is a number or not. A client side approach will never be at all secure for checking if form data conforms to requirements, but it does make things nicer for users, so both approaches should be taken.
David Dorward
You'll have to do both, actually. Client-side is nice for user interaction and reduces the problem of having to submit the form again after the server says what errors are present. Server-side is for validation.
Joey
+2  A: 

If you wish to risk using draft specs, you can use the number type:

<input name="foo" type="number">

(See also, the specification)

Browser support for this is currently very limited, but increasing. You will probably want to add JavaScript to simulate support in less bleeding edge browsers. There are various projects to do this, including jsh5f and webforms2.

Obviously, no matter which approach you take to the problem, you will still need a server side check of the data (you can never trust the client since any restrictions you impose there can be bypassed by the user).

David Dorward
what browsers support this?
Opera does, but not many beyond that - hence the use of JS.
David Dorward
A: 

Try this:

 <HTML>
       <HEAD>
       <SCRIPT type="text/javascript">

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

             return true;
          }

       </SCRIPT>
       </HEAD>
       <BODY>
          <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
       </BODY>
    </HTML>
MAS1
This fails to deal with pasted data.
David Dorward
this is just fine, thanks
@David Dorward, OP accepted my answer.
MAS1
@MAS1 — that doesn't prevent it having flaws.
David Dorward
@David Dorward, i agree with your point.
MAS1