如何在文本字段长度大于定义的数字时显示警报

New*_*Bie 1 html javascript

我是编程新手,我正在创建一个代码,通过它我如何限制用户在定义的数字内输入值。

我希望用户输入的字段值不超过 35 个字符或长度。

这是我的书面代码,但它不起作用

我使用 onkeyup 方法

function handleChange() {
    var x = document.getElementById("fname");
    var y = document.getElementById("lname");
    if ((x.value > 35) || (y.value > 35))
    {
      alert("value should less than 35");
    }
  }
Run Code Online (Sandbox Code Playgroud)
<form onkeyup="handleChange()">
    Enter your fname: <input type="text" id="fname">
    Enter your lname: <input type="text" id="lname">
</form>
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用 maxlength 属性从 HTML 中执行此操作。因此您不需要 handleChange 函数。用户将被简单地限制为一定数量的字符。更多信息在这里:https : //www.w3schools.com/tags/att_input_maxlength.asp

<input type="text" id="fname" maxlength="35">
<input type="text" id="lname" maxlength="35">
Run Code Online (Sandbox Code Playgroud)

或者你想做什么,但添加 .length

所以..

if ((x.value.length > 35) || (y.value.length > 35))
{
    alert("value should less than 35");
}
Run Code Online (Sandbox Code Playgroud)