Limit input box to 0-100

2019-01-14 13:01发布

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.

8条回答
不美不萌又怎样
2楼-- · 2019-01-14 13:49

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.

查看更多
Deceive 欺骗
3楼-- · 2019-01-14 13:52

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.

查看更多
登录 后发表回答