简体   繁体   English

将html输入框格式化为仅数字输入 - 正确格式化减号

[英]Formatting a html input box to numeric input only - Correctly formating the minus character

I'm trying to format a html text input box so that it only accepts numeric values (using javascript). 我正在尝试格式化html文本输入框,以便它只接受数值(使用javascript)。 This means the input can only be a digit, a minus or a dot/comma (a comma gets replaced with a dot anyway). 这意味着输入只能是数字,减号或点/逗号(无论如何,逗号都会被点替换)。

The thing is, a minus must be prevented if it is not the first character of the string. 问题是,如果它不是字符串的第一个字符,则必须防止减号。 Ex: "-30" is a valid input, but "80----20" is not. 例如:“ - 30”是有效输入,但“80 ---- 20”不是。 Does anyone has any idea on how to solve this? 有没有人知道如何解决这个问题?

 var div = document.getElementById("div"); function inputHandle(event, object){ var input = document.getElementById("value"); var comma = false; for (i=0; i<input.value.length; i++) { var array = input.value; if (input.value[i] == ".") { comma = true; } } if ((event.keyCode == 13) && (Number(input.value) < Number.MAX_SAFE_INTEGER)) { object.innerHTML = Number(input.value); } if ((event.charCode == 44) && (comma == false)) { input.value = input.value + "."; event.preventDefault(); } if (!((/^-?\\d*\\.?\\d*$/.test(event.key) == true) || (((event.charCode == 118) || (event.charCode == 99) || (event.charCode == 97)) && (event.ctrlKey)) || (event.keyCode == 8) || (event.keyCode == 46) || (event.keyCode >= 35 && event.keyCode <= 40) )) { event.preventDefault(); } if ((event.charCode == 46) && (comma == true)) { event.preventDefault(); } } 
 <div id="div"></div> <input type='text' onkeypress='inputHandle(event, div)' accept-charset='ISO-8859-1' id='value' name='coefficientvalue' placeholder='Enter a value...'> 

If you really need a input[type="text"] I think a regular expression is the best you could use. 如果你真的需要输入[type =“text”],我认为正则表达式是你可以使用的最好的。 The following Regex should work: 以下正则表达式应该工作:

/^-?\d*\.?\d*$/

You could check the input value on each input-event with this regex like the following: 您可以使用此正则表达式检查每个输入事件的输入值,如下所示:

/^-?\d*\.?\d*$/.test(input.value)

Otherwise you should use type="number" for your input element, like Andreas commented. 否则你应该使用type="number"作为输入元素,就像Andreas所评论的那样。

After testing the input you should use parseFloat to normalize the input, since the Regex would allow inputs like ".2" or "2.". 在测试输入后,您应该使用parseFloat来规范化输入,因为正则表达式将允许输入“.2”或“2”。

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

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