jquery: set min max input in option type number
Asked Answered
E

6

21

I have this part of code

<input type="number" min="2" max="10" step="2" id="contact" oninput="new_sum">

In the field I can insert a number > 10 and < 2.

How can I limit it?

Empire answered 22/6, 2014 at 17:22 Comment(2)
It is already limited. What exactly do you mean by "How can I limit it?"Agreed
I believe they are asking if you type a number into the input field. The limit isn't handled.Resuscitator
R
44

add an onchange function and set the value if it's out of the range.

 $(function () {
       $( "#numberBox" ).change(function() {
          var max = parseInt($(this).attr('max'));
          var min = parseInt($(this).attr('min'));
          if ($(this).val() > max)
          {
              $(this).val(max);
          }
          else if ($(this).val() < min)
          {
              $(this).val(min);
          }       
        }); 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="numberBox" type="number" min="2" max="10" step="2" id="contact"  />
Resuscitator answered 22/6, 2014 at 17:32 Comment(5)
you're right, I had a typo - ($this) instead of $(this). I've updated the answer and fiddle. Check them out.Resuscitator
yes it's correct now.Is it possible block the input text? it should work only with the buttonsEmpire
I'm not at a computer, but I would try setting the read only CSS property to true.Resuscitator
I'd use keyup rather than change so it can't be typed in.Letitialetizia
Just comparing two input values gave faulty result. Using Parseint($(this).Val()) worked for comparing two input numbers on input.Westernize
U
12

A simpler and dynamic way for not allowing the user to type or paste values outside the interval nor any other non-numeric character (without the need for manually parsing or detecting keys):

$('input[type=number]').on('mouseup keyup', function () {
  $(this).val(Math.min(10, Math.max(2, $(this).val())));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" step="2" id="contact">

If this specific event is only needed for a particular input use the id, i.e. $('#contact').on(...). Explanation: these Math functions compare with Infinity in the absence of an argument.

Note: mouseup can also be used to prevent the user to paste or use the arrows with the cursor.

Unwisdom answered 24/8, 2017 at 16:12 Comment(0)
G
5

The approach I've used here (though I've created a plugin to do so) is to check whether the entered value is in the range defined by the min and max attributes, if it is we keep that value; if not we test whether the entered value is less than the min value, if it is then we set the value to the min value and if not (implying that the value must be greater than the max) we set the value to the max attribute:

(function ($) {
    $.fn.restrict = function () {
        // returns the collection returned by the selector, over which we iterate:
        return this.each(function(){
            // binding a change event-handler:
            $(this).on('change', function(){
                // caching the 'this' (the current 'input'):
                var _self = this,
                    // creating numbers from the entered-value,
                    // the min and the max:
                    v = parseFloat(_self.value),
                    min = parseFloat(_self.min),
                    max = parseFloat(_self.max);
                // if it's in the range we leave the value alone (or set
                // it back to the entered value):
                if (v >= min && v <= max){
                    _self.value = v;
                }
                else {
                    // otherwise we test to see if it's less than the min,
                    // if it is we reset the value to the min, otherwise we reset
                    // to the max:
                    _self.value = v < min ? min : max;
                }
            });
        });
    };
})(jQuery);

$('#contact').restrict();

JS Fiddle demo.

This is somewhat naive, in that the restrict() plugin doesn't test whether the <input> element's type is of number (yet).

Edited to add a slight sanity check to check that the element is, in fact, of type="number":

(function ($) {
    $.fn.restrict = function () {
        return this.each(function(){
            if (this.type && 'number' === this.type.toLowerCase()) {
                $(this).on('change', function(){
                    var _self = this,
                        v = parseFloat(_self.value),
                        min = parseFloat(_self.min),
                        max = parseFloat(_self.max);
                    if (v >= min && v <= max){
                        _self.value = v;
                    }
                    else {
                        _self.value = v < min ? min : max;
                    }
                });
            }
        });
    };
})(jQuery);

JS Fiddle demo.

Gibbsite answered 22/6, 2014 at 19:13 Comment(2)
thank you!.Is it possible block the input text? it should work only with the buttonsEmpire
Not that I'm aware of, imagine how difficult that would be in, for example, a smart-phone or tablet.Gibbsite
M
1

You can have a generic function to do this on any input step elements --

 $(function () {

    var limitInput = function () {
        var value = parseInt(this.value, 10);
        var max = parseInt(this.max, 10);
        var min = parseInt(this.min, 10);

        if (value > max) {
            this.value = max;
        } else if (value < min) {
            this.value = min
        }
    };

    $("#numberBox").change(limitInput);
});

FIDDLE

Miguel answered 22/6, 2014 at 17:56 Comment(1)
@Empire - Sorry - Updated my answer and the fiddle as well.Miguel
C
1

jquery set min max input (all type)

set attribute min & attribute max in tag input

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<input type="tel" class="form-control text-right ltr" data-min_max data-min="0" data-max="100" data-toggle="just_number" />

you can change min & max

data-min="0" data-max="100"

Jquery

$(document).on('keyup', '[data-min_max]', function(e){
    var min = parseInt($(this).data('min'));
    var max = parseInt($(this).data('max'));
    var val = parseInt($(this).val());
    if(val > max)
    {
        $(this).val(max);
        return false;
    }
    else if(val < min)
    {
        $(this).val(min);
        return false;
    }
});

$(document).on('keydown', '[data-toggle=just_number]', function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) ||
         // Allow: Ctrl+C
        (e.keyCode == 67 && e.ctrlKey === true) ||
         // Allow: Ctrl+X
        (e.keyCode == 88 && e.ctrlKey === true) ||
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

EXAMPLE : jsfiddle

Canaigre answered 11/1, 2017 at 13:36 Comment(0)
S
0

You can write just with jquery:

$('#contact').prop('minLength', 2);
$('#contact').prop('maxLength', 10);
Serpent answered 27/4, 2016 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.