如何只允许一个“。” 在按键期间在javascript中?
我这里有一个代码:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
如何只允许一个“。” 在按键期间在javascript中?
我这里有一个代码:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
在回答之前,我将重申我在评论中所说的话:
如果用户粘贴了一堆句号怎么办?如果他们在控制台中编辑 javascript 以完全忽略此检查怎么办?确保您正确处理验证并且没有进行太多简化。
现在我们要自担风险,下面是您不允许用户.
在文本框中输入多个(句点)的方法:
document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
// 46 is the keypress keyCode for period
// http://www.asquare.net/javascript/tests/KeyCode.html
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
如果您真的想允许一个点,即使用户在其中粘贴文本,您也应该使用 keyup,而不是 keypress,并且您可以保留最后一个文本值以防需要恢复它。但缺点是输入值已经更改,并且您会在键入时看到它得到更正。
(function() {
var txt = document.getElementById('txt');
var prevValue = txt.value;
function allowOneDot(e) {
var dots = 0;
var length = txt.value.length;
var text = txt.value;
for(var i=0; i<length; i++) {
if(text[i]=='.') dots++;
if(dots>1) {
txt.value = prevValue;
return false;
}
}
prevValue = text;
return true;
}
txt.onkeyup = allowOneDot;
})();
<input type="text" id="test" onkeyup="floatOnly(this);"/>
<script>
function floatOnly(i){
{
if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>