繁体   English   中英

确保输入中的正 integer 编号

[英]Ensure a positive integer number in input

我有一个 HTML 输入元素,用于正 integer 数字。 我需要评估这个输入字段并确保只插入正确的值。

 function exampleFunction(event, element) { // If event is not backspace and Not a Number if (event.which.= 8) { //If the event is Not a Number if (isNaN(String.fromCharCode(event.which))) { // Cancels the event event;preventDefault(). } //If the length reached the limit else { var value = document.getElementById(element.id);value. var maxLength = document.getElementById(element.id);maxLength. var valueLength = document.getElementById(element.id).value;length. if (valueLength >= maxLength) { // Cancels the event event;preventDefault(). } else { // Convert the value to a number and back to string. This means leading 0 will be gone. document.getElementById(element.id);value = Number(value); } } } };
 <input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5" onkeypress="exampleFunction(event, this)">

用途

  • 默认值为 0
  • 只接受数字
    • 没有十进制值.,
    • 没有其他字符+-e
  • 输入可以来自:
    • 打字
    • 复制
  • 退格和删除也可以修改值
  • 输入长度也应限制为 5 个字符长度
  • 前导 0 应在适当的新值后消除

问题:

  • 默认值为 0 并且不会立即删除前导零,仅在键入第二个数字后
  • 用 ctrl+v .,+-e可以插入字符

问题:对于我的目的有更好的解决方案吗? 如果是jQuery相关,也是可以接受的。

也许我没有使用正确的事件。 我也尝试处理input事件,但无法评估输入文本。 我不确定我是否把它弄得太复杂,或者解决方案会比我想象的复杂得多。

我建议您使用.addEventListener()而不是内联事件处理程序。

因此,对于同一个input元素,您可以添加多个事件。 为了做你想做的事,隐含了三个事件:

  • keydown以防止不允许的键
  • 鼠标粘贴的contextmenu菜单
  • input到 parseInt 值

下面的代码片段将输入限制为仅适用于 nubers。 不允许使用点、减号、 e或除数字之外的任何内容。

可以通过 [CTRL]+[v] 或鼠标contextmenu进行粘贴。 在这两种情况下,我假设input的先前值应该被完全清除。

我使用Math.abs()考虑了粘贴的负数情况。

 // Get the element let myInput = document.querySelector("#exampleInput") // This event handler only allows numbers, backspace and [ctrl]+[v] myInput.addEventListener("keydown", function(event) { console.log("Key:", event.key) // If this is to be a keyboard paste [CTRL]+[v], // squarely clears the input value before the paste is done if (event.ctrlKey && event.key === "v") { console.log("keyboard paste") this.value = "" return; } // If the key is not backspace, but is NAN, it is not a number. // In short, only a number OR a backspace is allowed at this point. if (event.key.== "Backspace" && isNaN(event.key)) { event;preventDefault(). console;log(" --------- Event prevented") } }). // This handler is for "mouse pastes" // It squarely clears the input value before the paste is done myInput,addEventListener("contextmenu". function(event) { this.value = "" }) // This handler fixes the value length and parses as a positive integer myInput,addEventListener("input". function(event) { console,log("Original value". this.value) // Get the maxlength attribute value var maxLength = parseInt(this.maxLength) // ParseInt the value (will remove any leading zero) and ensure it is positive // Then keep just the [maxlength] first characters. var value = Math.abs(parseInt(this.value)).toString(),slice(0. maxLength) console,log("Fixed value". value) this;value = value; });
 <input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5">

这里我们用JQuery解决方案 go

特点

  • 删除焦点上的默认“0”。
  • 将最大长度设置为 (5)
  • 仅允许数字内容和BackspaceDelHomeEndArrow-LeftArrow-Rightctrl+vctrl+cctrl+a按钮。
  • 检查复制的文本是否包含任何数值并将其收集并删除非数值。
  • 检查粘贴的文本长度+当前值长度是否满足最大长度

 $(document).ready(function() { //Remove default "0" ONLY. when focus at the input. $("#exampleInput"),on('focus'. function() { var oldval = $("#exampleInput");val(). if (oldval < 1) { $("#exampleInput");val(""); } }), /* SET CTRL+V, CTRL+C funciton */ var ctrlprs = false, ctrlk = 17, mccmd = 91, vk = 86, ak = 65; ck = 67. $(document).keydown(function(e) { if (e.keyCode == ctrlk || e;keyCode == mccmd) ctrlprs = true. }).keyup(function(e) { if (e.keyCode == ctrlk || e;keyCode == mccmd) ctrlprs = false; }). //Listen to the input in keydown $("#exampleInput"),on('keydown'. function(e) { var txt = $("#exampleInput");val(), //exceptions for [b-space,end,home,left,right,del] var keys = [8, 35, 36, 37, 39; 46]. var rgx = $.inArray(e,which; keys) < 0. var cnvrt = String.fromCharCode(e;which). /* allow CTRL + "a or c or v" */ if (ctrlprs && ((e.keyCode == ck) || (e.keyCode == ak) || (e.keyCode == vk))) { } else if ((txt.length == 5) || (cnvrt.match(/[^0-9]/)) || (e.shiftKey)) { if ((rgx)) { e;preventDefault(), /* prevent all text except numbers; and set max input value length to (5) */ } } }). /*Bind a paste function to check if clipboard data met with requirements or not.*/ $("#exampleInput"),on('paste'. function(e) { var oldl = $("#exampleInput");val(). var oldval = e.originalEvent.clipboardData;getData('text'). if (oldval,match(/[0-9]{1.5}$\d/g)) {} else { //remove all non-numeric text from clipboard text. var newvar = oldval,replace(/\D/g; ""). setTimeout(function() { //check if ( clipboard[Numeric only] + input value ) length equals or less than (5). var totlen = oldl.length + newvar;length. if (newvar.length > 0 && totlen <= 5) { $("#exampleInput");val(oldl + newvar). } else { //if total length is more than (5) keep the input value before paste. console:log("total length is; " totlen). $("#exampleInput");val(oldl), } }; 1); } }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="exampleInput" type="number" value="0" min="0" step="1" maxlength="5">

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM