5

i see this question but none of the solutions support min and max values range

How to allow only numeric (0-9) in HTML inputbox using jQuery?

I see that http://jstepper.emkay.dk/ attempts to do this but seems very buggy as it allows you to enter multiple decimal places and other characters such as ";".

is there i way i can use one of these solutions and also say, only support min of 0 and max of 100 in the textbox entry?

Community
  • 1
  • 1
leora
  • 188,729
  • 360
  • 878
  • 1,366

8 Answers8

20

I am the author of jStepper and I just updated the plugin to be able to do what you like.

So give it a try again and see if it works now :)

EmKay
  • 1,089
  • 1
  • 13
  • 28
  • thanks alot . . . . is there anyway to not have the default 0 in front . . http://jstepper.emkay.dk/ ?? – leora Jan 07 '10 at 21:30
  • Remove it with a callback function ;) let me know if you don't know how to do that :) – EmKay Jan 08 '10 at 16:12
  • EmKay, this is a fantastic plugin! Now that I've buttered you up, can I use it for free in commercial applications? – adrianos Mar 05 '10 at 09:44
  • Thank you very much for the praising words :) Of course you can use it for what you like. A little reference in the script would be nice though :P Can I see it in action once it's up 'n running? :) – EmKay Mar 08 '10 at 12:03
  • 1
    That's great news, thanks! Yes, we'll put a credit for you in the script, but I won't be able to show you the site as it'll be used on a hospital administration intranet - sorry. If I find a use for it in a public page on a public site, I'll show you - mail me at adrian.emmott@gmail.com so I can let you know down the line. – adrianos Mar 17 '10 at 10:29
  • Question, why are decimals represented with a comma? – ctorx Oct 02 '13 at 20:22
  • As written in the documentation: "Set to ',' (comma) as default because it is the most common in my home country :oP". Look in the documentation on "decimalSeparator" at http://jstepper.emkay.dk/ to find out how to change it :) – EmKay Oct 03 '13 at 09:17
  • Copy and paste text into that and see what happen! – QMaster Sep 06 '14 at 21:58
  • Emkay I m trying to set minValue:100 .but,it doesn't allow to put above 100 value .???? $('#txtTesting').jStepper({minValue:100, maxValue:5000}); – Mr7-itsurdeveloper Sep 16 '14 at 06:56
7

HTML5 way of adding such fields. Works in Chrome and Safari:

<input type="range" min="0" max="100" step="1" />

A complete example:

<input id="picker" type="range" min="0" max="100" step="1" onchange="$('#pickerValue').text(this.value)" />
<div id="pickerValue"></div>
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 3
    this ONLY validates value against min/max if you use the arrow icons to change values. You can still type a number outside the min/max range. – Michael Johnston Dec 03 '13 at 23:21
3

Create a custom type of text box that only accepts ranges. Something like this should work:

function RangeTextBox(min, max) {
    this.min = min;
    this.max = max;
    this.textBox = $("<input type='text'>");

    // Disallow non-numbers from being typed in box
    this.textBox.keydown(function(event) {
        var isNotBackspaceOrDelete = event.keyCode != 46 && event.keyCode != 8;
        var isNotInteger = event.keyCode < 48 || event.keyCode > 57;
        if(isNotBackspaceOrDelete && isNotInteger) {
            event.preventDefault();
        }
    });
    // Check for a valid range
    this.textBox.keyup(function(event) {
        var textBox = event.target;
        var isNotInRange = (textBox.value < min) || (textBox.value > max);
        if (isNotInRange) {
            textBox.value = textBox.value.slice(0, -1);
        }
    });

    return this.textBox;
}

To use it in, simple create a new TextBox by calling new RangeTextBox(min, max). For example

$(document).ready(function() {
    $("body").append(new RangeTextBox(1, 18));
});

Disclaimer: This suffers from the same problem as listed by Harmen in the other answer of field not accepting a value like 2 for the number "26" if minimum value is 6 as 2 < 6. You could use a timer, or actually move this check outside of the keyup and keydown events, and check onblur or onchange instead. That would allow invalid data to enter the field though but its a lot less annonying.

Edit: This solution let's you enter anything, but flags all invalid input including out of ranges.

function RangeTextBox(min, max) {
    this.min = min;
    this.max = max;
    this.textBox = $("<input type='text'>");

    // Check for a valid range
    this.textBox.keyup(function(event) {
        var textBox = event.target;
        var value = parseInt(textBox.value);
        var isNotNumeric = !/^[0-9]+$/.test(textBox.value);
        var isOutsideRange = (value < min) || (value > max);
        if (isNotNumeric || isOutsideRange) {
            $(textBox).addClass('error');
        }
        else {
            $(textBox).removeClass('error');
        }
    });

    return this.textBox;
}

And the stylesheet:

<style type="text/css">
.error {
    color: red;
}
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 1
    Unfortunately you can still enter a higher number than `max`, if you hold a key for a long time (the `keyup` event only works for the last number you pressed). Also you can't type 56 when `min` is 6. – Harmen Jan 06 '10 at 14:41
3

Textbox MIN MAX - jQuery function

Here is a way to for example, "only support min of 0 and max of 100 in a textbox entry" using jQuery. It works by returning your entry to what it was before - if you enter a key that results in the value being less than MIN or more that MAX. You can set a flag to accept only integers.

The HTML tag would look like this: (JSFIDDLE)

<input type="text" class="maxmin" min="0" max="100" intOnly="true" />

Then you'd run this JavaScript in your document ready code:

// Run this on document ready to allow only numbers between
// max and min to be entered into textboxes with class="maxmin".
// Attributes max, min, and intOnly="true/false" are set in the tag.
// Min should probably be "0" or "1", or max and min could be single digits.
// Otherwise for example, if min=5, you couldn't enter 23 because 2 < 5.
$(".maxmin").each(function () {

    var thisJ = $(this);
    var max = thisJ.attr("max") * 1;
    var min = thisJ.attr("min") * 1;
    var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";

    var test = function (str) {
        return str == "" || /* (!intOnly && str == ".") || */
            ($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
            (!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
            // commented out code would allow entries like ".7"
    };

    thisJ.keydown(function () {
        var str = thisJ.val();
        if (test(str)) thisJ.data("dwnval", str);
    });

    thisJ.keyup(function () {
        var str = thisJ.val();
        if (!test(str)) thisJ.val(thisJ.data("dwnval"));
    })
});

I'm new to this, so any constructive comments would be appreciated.

Community
  • 1
  • 1
StormDog
  • 91
  • 6
1

Here is an example of how your script could look like:

var value, min=6, max=100;

function isNumberPressed(k) {
    // 48-57 are number 0-9 on a normal keyboard, 96-105 are keypad numbers
    return (k > 47 && k < 58) || (k > 95 && k < 106) ? true : false;
}

function isValidNumber(v){
    // Check if a valid number is entered
    return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}

$(document).ready(function() {
    $("#test").keydown(function(e) {
        // See if a valid key is pressed
        if(isNumberPressed(e.keyCode)){
            if(isValidNumber($(this).val())) value = $(this).val();
        } 
        // Do nothing if unallowed keys are pressed
        else if(e.keyCode != 46 && e.keyCode != 8) return false;
    }).keyup(function(){
        // If the value, including the latest number that's added, is not valid (to high or to low), show the old value again
        if(isValidNumber($(this).val()) == false){
            $(this).val(value);
        }
    });
});

But it has a big disadvantage, you can't enter 26 if the minimum is 6, because 2 < 6. This is not a problem if you have a minimum less than or equal to 10.

However, if your minimum is more than 10, you could consider this code:

var timer, min=36, max=100;

function isValidNumber(v){
    // Check if a valid number is entered
    return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}

$(document).ready(function() {
    $("#test").keydown(function(e) {
        that = this;

        // Clear the timer
        if(timer)
            clearTimeout(timer);

        // Set a new timer with a delay of one second
        timer = setTimeout(function(){
            if(isValidNumber($(that).val()) == false) $(that).addClass('error');
            else $(that).removeClass('error');
        }, 1000);        
    });
});

It checks the input with a delay of one second. You need some CSS code for this, for example:

input.error {
    border: 2px solid red;
}

Both scripts check the values on the fly, which is a great method.

Harmen
  • 22,092
  • 4
  • 54
  • 76
1

I've created an jQuery SpinControl that supports min, max and step. It first checks if a SpinControl already is supported by the browser (Opera), before it adds a custom one.

jerone
  • 16,206
  • 4
  • 39
  • 57
0

I searched and finally i understand entered value must be check in three event. keydown, keypress and keyup and any of them has own responsibilities. keypress: Check the key pressed and decided about entered character. Then if it is numeric let it otherwise prevent the action. As you can see i tried to check range here

//var final = val + String.fromCharCode(charCode);        
//alert(final);        
//if (final < min || final > max)
// return false;       

but we just have new character and value before that. so that is wrong way if we try to check sum of them because maybe user selected some part of the value and new character standing rather. suppose max range is 100 and we have "345" in Input and user selected "34" now user press "2" and the result must be "25", but sum of "345" + "2" is 347 and function prevent that. So i decided to use keyup event to check range and correct value. Finally keydown used to check up and down arrow and control value when browser support HTML5 number type of input without changing like keypress so you can don't use that.

I wrote a simple script and hope that help. You can see it in http://jsfiddle.net/QMaster/r4hwr3a6/

QMaster
  • 3,743
  • 3
  • 43
  • 56
0

JStepper have a bug, I try the tester in their site. http://jstepper.emkay.dk/Default.aspx

apple the rules, but i can input the text : 8778.09999

Cheung
  • 15,293
  • 19
  • 63
  • 93
  • If you just use the rules that are on the testing page to begin with, there is a maxValue of 23. This means that if you input any value higher than this, it will revert to the value 23. I have just tried it and after I pasted in your value (8778.09999), it reverted to 23. Is this the "bug" you're seeing? – EmKay May 05 '15 at 14:17