Technology Lover
Technology Lover

Reputation: 259

HTML Text Input allow only two-digit Numeric input

I am new to JQuery world and I am trying to limit the number of digits in some of the text field inputs in the webpage that I am working on it right now. I would like to allow the user:

  1. to enter a number of two digits only
  2. the number should not exceed the value of 12, so he can enter numbers from 0 to 12 such as; 8, 11, 6.5

How can I do that?

Here's what I have done so far. HTML Code:

<input type="text" class="txt input-sm" />
<input type="text" class="txt input-sm" />

JQuery Code:

<script>
            $(function(){
                $(".txt").on("keypress", function(){
                    if($(".txt").val().length > 2)
                    {
                        this.value = parseFloat(this.value).toFixed(2);
                    }
                });
            });
    </script>

Upvotes: 1

Views: 10180

Answers (4)

Skeets
Skeets

Reputation: 4828

None of the answers here are ideal. Here is my solution:

$( function() {
  $(document).on('input', '.spinner', function() {
    
    var allowedDigits = 2;
    var length = $(this).val().length;
    var max = parseInt($(this).attr("max"));
    
    // appears there is a bug in the latest version of Chrome. When there are multiple decimals,
    // the value of a number type field can no longer be accessed. For now, all we can do is clear it
    // when that happens
    if($(this).val() == ""){
      $(this).val("");
    }
    
    if ($(this).val().indexOf('.') != -1) {
      allowedDigits = 3;
    }
   	
    if(length > allowedDigits){
      $(this).val($(this).val().substring(1));
 	}
    
    if($(this).val() > max && max > 0){
      $(this).val($(this).val().substring(1));
    }
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="spinner" type="number" min="0" value="00" max="12">

This will allow you to type in any number that is 2 digits and below 12, without interruption. It will drop off the leftmost number when there is too many digits.

Upvotes: 0

bowheart
bowheart

Reputation: 4676

So I actually completed a solution to this question two days ago, but I had to leave before I could post an answer. If you still need help, here's something to look at, though it probably has more features than you need--I was having fun :)

$(".txt").on("keyup", function(event) {

    // don't handle backspace, delete, pgup/pgdn, home/end, or arrow keys:
    if (event.keyCode === 8 || event.keyCode === 46 || event.keyCode >= 33 && event.keyCode <= 40) return false;

    var currentEl = $(this);
    var value = $(currentEl).val();

    // remove letters...
    value = value.replace(/[^0-9.-]/g, "");

    var hasDecPlace = value.match(/\./);

    // separate integer from decimal places:
    var pieces = value.split('.');
    var integer = pieces[0].replace('-', '');
    var decPlaces = ""
    if (pieces.length > 1)
    {
        pieces.shift();
        decPlaces = pieces.join('').replace('-', '');
    }

    // handle numbers greater than 12.00... :
    if (parseInt(integer) > 12 || parseInt(integer) === 12 && parseInt(decPlaces) > 0)
    {
        integer = "12";
        decPlaces = getZeroedDecPlaces(decPlaces);
        alert("number must be between 0.00 and 12.00");
    } // ...and less than 0:
    else if (parseInt(integer) < 0)
    {
        integer = "0";
        decPlaces = getZeroedDecPlaces(decPlaces);
        alert("number must be between 0.00 and 12.00");
    }

    // handle more than two decimal places:
    if (decPlaces.length > 2)
    {
        decPlaces = decPlaces.substr(0, 2);
        alert("number cannot have more than two decimal places");
    }

    var newVal = hasDecPlace ? integer + '.' + decPlaces : integer;

    $(currentEl).val(newVal);
});

function getZeroedDecPlaces(decPlaces) {
    if (decPlaces === '') return '';
    else if (decPlaces.length === 1) return '0';
    else if (decPlaces.length >= 2) return '00';
}

--First of all, handle the keyup event--values aren't added to inputs until after keypress or keydown

--Don't handle certain keys (return false). You can add more to this list.

--Next, an unorthodox approach, handle the number as a string: If you really don't want to use a <input type="number" /> tag, resort to regex to take letters and other junk out of the "number".

--Now, first, determine if there is a decimal point so you can reconstruct the "number" (string) later. Next, separate the integer from the decimal places.

--Now handle numbers greater than 12.00 or less than 0.00 by parsing the integer (and the decimal places, if the number === 12). I used a function (getZeroedDecimalPlaces) to avoid adding extra zeroes to, or removing numbers from, the user's string.

--Next limit the number of decimal places. I don't know if you wanted this. I limited it to two decimal places, but it can be set to whatever.

--Finally, reconstruct the string and stick it in the input

Here is the JSFiddle

Upvotes: 0

jmore009
jmore009

Reputation: 12923

you can use jQuery to remove the unwanted key characters then check to see if the value is greater than 12. The first event is keydown to see if the character pressed is allowed. I added another event for keyup because the value wasn't being registered until after "keyup"

$(".txt.input-sm").keydown(function (event) {

    //prevent using shift with numbers
    if (event.shiftKey == true) {
        event.preventDefault();
    }

    if (!((event.keyCode == 190) || (event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)) {
        //not a number key or period so prevent
        event.preventDefault();
    }
});

$(".txt.input-sm").keyup(function (event) {

    var number = parseFloat($(this).val());
    if(number > 12){
       $(this).val("");
    }
});

FIDDLE

UPDATE

This is tricky because of the decimal but you can do something like use a counter to track clicks.

NEW FIDDLE

Upvotes: 1

Damjan Pavlica
Damjan Pavlica

Reputation: 33973

<input type="number" min="0" max="12">

Upvotes: 0

Related Questions