Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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>
share|improve this question
    
so you want to have numbers from 0 to 12, but what about numbers in between? Do you want to enforce some limit to decimal places as well? – W3AVE Jan 10 '15 at 18:15

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

share|improve this answer
    
thank you very much for your help. However, I need your help in the following: when the user tries to enter the third digit, I want the system to prevent him from entering that digit (with keeping the other two digits he entered) and to show him a meaningful message. How can I do that in your code? – Technology Lover Jan 11 '15 at 18:31
    
@TechnologyLover updated my post with a new fiddle – jmore009 Jan 11 '15 at 20:43
<input type="number" min="0" max="12">
share|improve this answer
    
You need to add step attribute to handle float numbers as 6.5 – A. Wolff Jan 10 '15 at 18:16

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

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.