[jquery] Number input type that takes only integers?

I'm using the jQuery Tools Validator which implements HTML5 validations through jQuery.

It's been working great so far except for one thing. In the HTML5 specification, the input type "number" can have both integers and floating-point numbers.

This seems incredibly short-sighted since it will only be a useful validator when your database fields are signed floating-point numbers (for unsigned ints you'll have to fall back to pattern validation and thus lose extra features like the up and down arrows for browsers that support it).

Is there another input type or perhaps an attribute that would restrict the input to just unsigned integers?

I couldn't find any, thanks.

EDIT

Ok, guys, I appreciate your time and help, but I see many undeserved up-voting going on :D.

Setting the step to 1 is not the answer since it doesn't restrict the input. You can still type a negative floating-point number into the textbox.

Also, I am aware of pattern validation (I mentioned it in my original post), but that was not part of the question.

I wanted to know if HTML5 allowed restricting an input of type "number" to positive integer values. To this question the answer, it seems, would be "no, it does not".

I didn't want to use pattern validation because this causes some drawbacks when using jQuery Tools validation, but it now seems that the specification doesn't allow for a cleaner way to do this.

This question is related to jquery html validation jquery-tools

The answer is


Yes, HTML5 does. Try this code (w3school):

<!DOCTYPE html>
<html>
<body>

<form action="">
  Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5" />
  <input type="submit" />
</form>

</body>
</html>

See the min and max paremeter? I tried it using Chrome 19 (worked) and Firefox 12 (did not work).


The best you can achieve with HTML only (documentation):

_x000D_
_x000D_
<input type="number" min="0" step="1"/>
_x000D_
_x000D_
_x000D_


Shortest

This is size improvement of R. Yaghoobi answer

_x000D_
_x000D_
<input type="number" oninput="this.value|=0"/>
_x000D_
_x000D_
_x000D_

We use here standard shorthand for "OR" operator e.g 9 | 2 = 11 in binary: 0b1001 | 0b1010 = 0b1011 . This operator first cast numbers to integers in implicit way and then do OR. But because OR with zero don't change anything so number is cast to integer. OR with non-number string gives 0.


var valKeyDown;
var valKeyUp;


function integerOnly(e) {
    e = e || window.event;
    var code = e.which || e.keyCode;
    if (!e.ctrlKey) {
        var arrIntCodes1 = new Array(96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 9, 116);   // 96 TO 105 - 0 TO 9 (Numpad)
        if (!e.shiftKey) {                          //48 to 57 - 0 to 9 
            arrIntCodes1.push(48);                  //These keys will be allowed only if shift key is NOT pressed
            arrIntCodes1.push(49);                  //Because, with shift key (48 to 57) events will print chars like @,#,$,%,^, etc.
            arrIntCodes1.push(50);
            arrIntCodes1.push(51);
            arrIntCodes1.push(52);
            arrIntCodes1.push(53);
            arrIntCodes1.push(54);
            arrIntCodes1.push(55);
            arrIntCodes1.push(56);
            arrIntCodes1.push(57);
        }
        var arrIntCodes2 = new Array(35, 36, 37, 38, 39, 40, 46);
        if ($.inArray(e.keyCode, arrIntCodes2) != -1) {
            arrIntCodes1.push(e.keyCode);
        }
        if ($.inArray(code, arrIntCodes1) == -1) {
            return false;
        }
    }
    return true;
}

$('.integerOnly').keydown(function (event) {
    valKeyDown = this.value;
    return integerOnly(event);
});

$('.integerOnly').keyup(function (event) {          //This is to protect if user copy-pastes some character value ,..
    valKeyUp = this.value;                          //In that case, pasted text is replaced with old value,
    if (!new RegExp('^[0-9]*$').test(valKeyUp)) {   //which is stored in 'valKeyDown' at keydown event.
        $(this).val(valKeyDown);                    //It is not possible to check this inside 'integerOnly' function as,
    }                                               //one cannot get the text printed by keydown event 
});                                                 //(that's why, this is checked on keyup)

$('.integerOnly').bind('input propertychange', function(e) {    //if user copy-pastes some character value using mouse
    valKeyUp = this.value;
    if (!new RegExp('^[0-9]*$').test(valKeyUp)) {
        $(this).val(valKeyDown);
    }
});

have you tried setting the step attribute to 1 like this

<input type="number" step="1" /> 

Set the step attribute to 1:

<input type="number" step="1" />

This seems a bit buggy in Chrome right now so it might not be the best solution at the moment.

A better solution is to use the pattern attribute, that uses a regular expression to match the input:

<input type="text" pattern="\d*" />

\d is the regular expression for a number, * means that it accepts more than one of them. Here is the demo: http://jsfiddle.net/b8NrE/1/


The integer input would mean that it can only take positive numbers, 0 and negative numbers too. This is how I have been able to achieve this using Javascript keypress.

<input type="number" (keypress)="keypress($event, $event.target.value)" >

keypress(evt, value){
  
    if (evt.charCode >= 48 && evt.charCode <= 57 || (value=="" && evt.charCode == 45))       
    {  
      return true;
    }
    return false;
}

The given code won't allow user to enter alphabets nor decimal on runtime, just positive and negative integer values.


Currently, it is not possible to prevent a user from writing decimal values in your input with HTML only. You have to use javascript.


Just putting it in your input field : onkeypress='return event.charCode >= 48 && event.charCode <= 57'


Pattern is nice but if you want to restrict the input to numbers only with type="text", you can use oninput and a regex as below:

<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>

I warks for me :)


The easy way using JavaScript:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >

This is not only for html5 all browser is working fine . try this

onkeyup="this.value=this.value.replace(/[^0-9]/g,'');"

<input type="text" name="PhoneNumber" pattern="[0-9]{10}" title="Phone number">

Using this code, the input to the text field limits to enter only digits. Pattern is the new attribute available in HTML 5.

Pattern attribute doc


In the Future™ (see Can I Use), on user agents that present a keyboard to you, you can restrict a text input to just numeric with input[inputmode].


Set step attribute to any float number, e.g. 0.01 and you are good to go.


Maybe it does not fit every use case, but

<input type="range" min="0" max="10" />

can do a fine job: fiddle.

Check the documentation.


Short and user friendly

This solution supports tab, backspace, enter, minus in intuitive way

_x000D_
_x000D_
<input type=text onkeypress="return /^-?[0-9]*$/.test(this.value+event.key)">
_x000D_
_x000D_
_x000D_

however it not allow to change already typed number to minus and not handle copy-paste case.

As alternative you can use solution based on R. Yaghoobi answer which allow to put minus and handle copy-paste case, but it delete whole number when user type forbidden character

_x000D_
_x000D_
<input type=text oninput="this.value= ['','-'].includes(this.value) ? this.value : this.value|0">
_x000D_
_x000D_
_x000D_


_x000D_
_x000D_
<input type="number" oninput="this.value = Math.round(this.value);"/>
_x000D_
_x000D_
_x000D_


From the specs

step="any" or positive floating-point number
Specifies the value granularity of the element’s value.

So you could simply set it to 1:


Pattern are always preferable for restriction, try oninput and min occur 1 for inputting only numbers from 1 onwards

<input type="text" min="1" oninput="this.value=this.value.replace(/[^0-9]/g,'');"
                                value=${var} >


I was working oh Chrome and had some problems, even though I use html attributes. I ended up with this js code

$("#element").on("input", function(){
        var value = $(this).val();

        $(this).val("");
        $(this).val(parseInt(value));

        return true;
});

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to jquery-tools

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools Number input type that takes only integers?