限制文本框输入2到998之间的数字无效

Restrict Textbox from enter numbers from 2 to 998 not working

本文关键字:之间 数字 无效 文本 输入      更新时间:2023-09-26

我有一个文本框,如下所示;

<input type="text"  id="rankId" onkeypress="return validate(event)"/>

它应该只接受2到998之间的值。我写了一个这样的函数;

function validate(key)
{
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('rankId');
//comparing pressed keycodes
if (!(keycode==8 || keycode==46)&&(keycode < 48 || keycode > 57))
{
return false;
}
else
{
//Condition to check textbox contains 3 numbers or not
if (phn.value.length <3)
{
return true;
}
else
{
return false;
}
}
}

该功能仅适用于数字和3个数字限制。如何将其限制为从2到998的数字?请帮忙。

在blur事件中调用一个函数,并执行以下操作

var value =  document.getElementByID("rankId").value;
if(value < 2 || value > 998)
   document.getElementByID("rankId").value = "";

调用Javascrift的属性value以获取输入值。。。

  var phn = document.getElementById('rankId').value;

然后

 function validate(key)
    {
    //getting key code of pressed key
    var keycode = (key.which) ? key.which : key.keyCode;
    var phn = document.getElementById('rankId').value;
    //This is a Javascript!!! and you have to define the function...
    //comparing pressed keycodes
    if (!(keycode==8 || keycode==46)&&(keycode < 48 || keycode > 57))
    {
    return false;
    }
    else
    {
    //Condition to check textbox contains 3 numbers or not
    if (phn.length <3)
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    }