【问题标题】:Input Number - max constraint validation not working输入数字 - 最大约束验证不起作用
【发布时间】:2019-06-08 09:19:55
【问题描述】:

我有一个输入字段number,您可以在下面的 sn-p 上看到它,这似乎有效,但有一个错误。

当您插入 89 时,它会起作用并返回应有的最大值。

但如果第一个数字小于 7,则不起作用(任何小于 69 的数字)。它只比较第一个数字而不是最后一个数字。

如何正确使用它?

谢谢!

<input type="number" name="teste" id="teste"
       value="0" min="0" max="7" 
       onchange="javascript: if (this.value > this.max) this.value = this.max;" />

【问题讨论】:

  • 为什么你有一个 onchange 处理程序呢? w3schools.com/tags/att_input_max.asp
  • @Dellirium 请不要链接到或使用 w3schools。
  • @ChrisG 是否违反 stackoverflow 政策?我不使用 w3s,但是对于像 input max 这样简单的事情,它确实传达了信息,并且是排名第一的 google 结果,因此我将其链接。
  • @Dellirium 它需要远离第一名,这是你不应该链接到它的原因之一。这不违反政策,但至少违反了良好的品味。
  • javascript: 标签在这里没用

标签: javascript html validation input


【解决方案1】:

可能在比较之前将值转换为整数 像这样:

   &lt;input type="number" name="teste" id="teste" value="0" min="0" max="7" onchange="javascript: if (parseInt(this.value) &gt; this.max) this.value = this.max;" /&gt;

【讨论】:

  • 正是我需要的。谢谢!
【解决方案2】:

HTML 属性只能包含文本(不能包含其他类型),因此您正在使用lexicographical order。请比较:

console.log("27" > "7");
console.log(27 > 7);

由于按字母顺序排列数字不是很有用,你可以extract numbers from strings

console.log("27", typeof "27");
console.log(parseInt("27", 10), typeof parseInt("27", 10));

现在,第二个参数(基数或基数)应该在大多数情况下默认为 10,但设置明确避免意外。

【讨论】:

    【解决方案3】:

    考虑代码:if (this.value &gt; this.max) this.value = this.max;

    在函数中,inputmax 的值被用作文本(或字符串数​​据类型)并进行比较。你的目的是比较数字。该示例是这样做的:

    HTML:

    <body>
    
        Result: <p id="result">0</p>
    
        <input type="number" name="teste" id="teste" 
               value="0" min="0" max="7" 
               onchange="test(this)" />
    
        <script src="test.js"></script>
    
    </body>
    


    test.js:

    function test(elmnt) {
    
        console.log(typeof elmnt.value); // this returns "string"
        console.log(typeof elmnt.max);   // this returns "string"
    
        // convert string numbers to integer numbers
        let intVal = parseInt(elmnt.value);
        let maxInt = parseInt(elmnt.max);
    
        console.log("Input: " + intVal);
    
        if (intVal > maxInt) {
            intVal = maxInt;
        }
    
        console.log("Result: " + intVal);
        document.getElementById("result").innerHTML = intVal;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-07
      • 1970-01-01
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多