如何在html文本字段中限制数字的最大值和最小值 [英] How to limit the max and min value of number in html text field

查看:300
本文介绍了如何在html文本字段中限制数字的最大值和最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本字段,应允许用户输入数字,最大长度应为2,最大值应为31,最小值应为1
我能够前2个条件但不知道最后2个条件

I have a text field which should allow the user to enter numbers,the maximum length should be 2 and the maximum value should be 31 and minimum value should 1 I am able to first 2 conditions but dont know the last 2 conditions

有人可以帮助我吗?

<input type="text"  name = "ccdate" class="form-control" maxlength="2" onkeypress="return isNumber(event)" >


function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

NOte 我不想使用HTML5输入类型=数字

NOte I dont want to use HTML5 input type="number"

推荐答案

试试这个(Purely Jquery方法):

Try this(Purely Jquery approach):

HTML:

<input type="text"  name = "ccdate" class="form-control" maxlength="2">
<div id="div1"></div>

JQUERY:

$('[name="ccdate"]').keyup(function(){
  if(parseInt($(this).val()) > 31){
    $('#div1').html('value cannot be greater then 31');
    $(this).val('');
  }
  else if(parseInt($(this).val()) < 1)
  {
    $('#div1').html('value cannot be lower then 1');
    $(this).val('');
  }
  else
  { $('#div1').html(''); }
});

工作演示

编辑: - (根据提问评论检查用户输入的字符串或数字):

EDIT :-(as per questioner comment to check user entered string or number):

$('[name="ccdate"]').keyup(function(){
  if(isNaN($(this).val()))
   {
    $('#div1').html('entered string');
    $(this).val('');
   }
  else if(parseInt($(this).val()) > 31){
    $('#div1').html('value cannot be greater then 31');
    $(this).val('');
  }
  else if(parseInt($(this).val()) < 1)
  {
    $('#div1').html('value cannot be lower then 0');
    $(this).val('');
  }
  else
  { $('#div1').html(''); }
});

工作演示

编辑: - (纯Javascript方法) (只需在文本框中提供一个唯一的 id 't1'

EDIT :- (Pure Javascript approach)(Just provide a unique id to your textbox say 't1')

document.getElementById('t1').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 1 || parseInt(this.value) > 31 || isNaN(this.value)) ? "" : (this.value)
});

工作演示

这篇关于如何在html文本字段中限制数字的最大值和最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆