18

I have an input box that takes values from 0-100. I want to prevent users from writing anything larger or smaller.

I've been using the jquery keyfilter plugin to limit the input of a field: http://code.google.com/p/jquery-keyfilter/

This plugin can limit the input to numerals, but not within a range. How do I prevent users from entering numbers that would exceed the range. Thanks.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Jourkey
  • 33,710
  • 23
  • 62
  • 78

8 Answers8

43

Use plain Javascript like this:

<script>
  function handleChange(input) {
    if (input.value < 0) input.value = 0;
    if (input.value > 100) input.value = 100;
  }
</script>

Then declare the input box like this:

<input type="text" onchange="handleChange(this);" />

Because you have hooked this function to onchange(), it will work even if a user copy / pastes something into the input box.

KJ Saxena
  • 21,452
  • 24
  • 81
  • 109
  • Thanks a lot. How would I bind the event so that it's not inline? – Jourkey Sep 05 '09 at 19:41
  • 12
    -1 Coercing acceptable values is a horrible interface design. An inattentive user could easily enter unintended data this way. You should flag the data as invalid and let the user choose how to adjust it. Perhaps, they've just typed into the wrong box and the value really belongs elsewhere, where it would be valid. – tvanfosson Sep 05 '09 at 20:29
  • I definitely see your point. But isn't this exactly what a slider does? When you try to go over 100, it just forces you back to 100/the max. – Jourkey Sep 05 '09 at 21:30
  • 1
    @Jourkey -- yes, but it's a different type of interface element. You can't force it past the limit. With a textbox you could type 134 and not notice that it silently changes it to 100. Ideally you'd use an input with validation (server side) that gets hidden by javascript and replaced by a slider that fills in the input values. That way it presents the appropriate interface for most users, but degrades gracefully when there is no javascript. – tvanfosson Sep 05 '09 at 22:28
  • 1
    I like that you included the HTML input too. And not just the JavaScript. For people just learning this stuff it could really leaving you scratching your head on tying the pieces together. – eaglei22 Jun 26 '15 at 15:02
11

I'd suggest using the jQuery Validation plugin. Very flexible and extensible. To handle your range query the following. It will valied that any input in your form marked with the "percentage" class is present and falls in the given range.

$("#myform").validate({
  rules: {
    percentage: {
      required: true,
      range: [0, 100]
    }
  }
});

<input id="percent" name="percent" class="percentage" />

The reason that I suggest using the plugin is that it handles many validation situations out of the box, relieving you of the responsibility to write validation code for many scenarios -- you can expend your creative effort in better ways. It's also used by many people and so has the added advantage of being improved by a large community.

Update: Also, you may want to consider an alternative input mechanism, such as a slider (demo) that will constrain the data in a way that isn't subject to user error -- or at least not this particular type of error.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Thanks for your help. I have a slider as well as an input box. The slide is hooked to the input box and vice versa. The reason why I'm not using validation is because entering a too big value would just set the slider to 100%, but the input box would not follow, and that's just odd. Also the blur event might take the user away from the page / hide the input field, and the user would be left with a broken value without ever seeing the error. – Jourkey Sep 05 '09 at 21:28
  • @Jourkey -- see my comment on the accepted answer. I would hide the input when creating the slider. If that's not an option, at the very least I would throw up a warning and not let the form submit rather than coercing the value. – tvanfosson Sep 05 '09 at 22:31
11

HTML5 added several new input types, including number.

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

New input types that are not supported by older web browsers, will behave as <input type="text">.

Runnable example from W3Schools.

pneumatics
  • 2,836
  • 1
  • 27
  • 27
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
6

You can use Math.min() and Math.max():

const val = Math.min(100, Math.max(0, val));

See documentation for more info:

lokarkristina
  • 305
  • 4
  • 9
jilykate
  • 5,430
  • 2
  • 17
  • 26
2

document.getElementById("test_id").onkeyup = function() {
  var input = parseInt(this.value);
  if (input < 0 || input > 100)
    console.log("Value should be between 0 - 100");
  return;
}
<input type="text" id="test_id" />
adiga
  • 34,372
  • 9
  • 61
  • 83
Xinus
  • 29,617
  • 32
  • 119
  • 165
1

You just need to test the value of the field after each keystroke and before it is sent to the field (for example with a keypress event handler) - if the new keystroke would create a value too high then reject the key press.

For example - if the current value is 20 and the user tries to type a third number, you should reject the key press by returning false from the event handler. Basically the only third character that you should allow is "0" and only if the current field value is "10".

Guss
  • 30,470
  • 17
  • 104
  • 128
  • 1
    I would advise not using this method. At least change it to the blur event. People don't like their input getting validated before they're done entering. Not to mention, it's possible to populate text boxes without keypresses. (mouse paste) – recursive Sep 05 '09 at 20:05
0

by jQuery to do this

<input type="number" name="quantity">

if number not between 0 - 100 then empty input field

<script>
    $("input[name='quantity']").change(function() {
      number = $("input[name='quantity']").val()
       if( number <= 0 || number >= 100 ) {
           $("input[name='quantity']").val("");
           alert("0 - 100");
         }
       });
</script>
-3

If its just for number of characters not exceeding 20 (for example), then you can use

<input type="text" name="usrname" maxlength="20" />

If you need to handle some other cases in the input field, then a function would be a better option.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Vivek
  • 61
  • 1
  • 8