Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit input box to 0-100

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.

like image 494
Jourkey Avatar asked Sep 05 '09 19:09

Jourkey


2 Answers

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.

like image 107
KJ Saxena Avatar answered Oct 05 '22 14:10

KJ Saxena


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.

like image 45
tvanfosson Avatar answered Oct 05 '22 15:10

tvanfosson