number only html form
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 num开发者_运维百科bers would show, please help
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).
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/
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>
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.
To input only number you can create a jQuery function to validate the characters you type in the input textbox
Your html code might be like this:
<input class="integerInput" type="text">
and your jQuery function might be like this:
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, ''); // numbers only
});
});
I have a OneLiner:
<input type="number" onkeypress="return /[0-9]/i.test(event.key)">
精彩评论