How to make type= number to positive numbers only
Add a min
attribute
<input type="number" min="0">
HTML input for Positive Whole Numbers Only (Type=number)
To disallow any input but numeric, you may use
<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
^------------....
<form id="mfrm"><table> <tr> <td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td> <td><input type="Submit"/></td> </tr></table>
Is there any way to prevent input type= number getting negative values?
Use the min
attribute like this:
<input type="number" min="0">
How to make HTML input tag only accept numerical values?
HTML 5
You can use HTML5 input type number to restrict only number entries:
<input type="number" name="someid" />
This will work only in HTML5 complaint browser. Make sure your html document's doctype is:
<!DOCTYPE html>
See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.
JavaScript
Update: There is a new and very simple solution for this:
It allows you to use any kind of input filter on a text
<input>
,
including various numeric filters. This will correctly handle
Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations,
non-typeable keys, and all keyboard layouts.
See this answer or try it yourself on JSFiddle.
For general purpose, you can have JS validation as below:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>
If you want to allow decimals replace the "if condition" with this:
if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))
Source: HTML text input allow only numeric input
JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/
Related Topics
Using Text-Align Center in Colgroup
Relative Url to a Different Port Number in a Hyperlink
How to Extract Url and Link Text from HTML in Perl
Why Does Inline-Block Cause This Div to Have Height
Why Does Overflow Hidden Stop Floating Elements Escaping Their Container
Wait Until an HTML5 Video Loads
Remove Default Text/Placeholder Present in HTML5 Input Element of Type=Date
Adding Custom Attribute (Html5) Support to Jsf 2.0 Uiinput Component
Does the <Li> Tag in HTML Have an Ending Tag
CSS Grid - Maximum Number of Columns Without Media Queries
Is Using <Li> Without Enclosing <Ul> Tags Dangerous
How to Set Height for the Drop Down of Select Box
How to Maintain Scroll Position in MVC