【发布时间】:2019-02-24 17:02:42
【问题描述】:
我有一个<form>,我试图比较input 的value 和max,以便如果value 超过max,我会应用不同的样式到输入(如红色边框)。假设我有这样的输入:
<input id="inp_1" type="text" numeric-only="" max="50">
假设我有三个输入值(9、49 和 59)。我一会儿再回来。
这是我的 js 代码,它获取输入并检查 value 和 max:
var activeInpId = document.activeElement.id;
var activeInpVal = document.activeElement.value;
var activeInpMax = document.activeElement.max;
var pickElement = document.getElementById(activeInpId);
//console 1
console.log("The entered value is (" + activeInpVal + ") and it's max is (" + activeInpMax + ")");
if( activeInpVal > activeInpMax ){
//console 2
console.log("Error. Value (" + activeInpVal + ") exceeds max (" + activeInpMax + ")");
pickElement.style.border = '2px solid';
pickElement.style.outline = 'none';
pickElement.style.borderColor = '#E60000';
pickElement.style.boxShadow = '0 0 10px #E60000';
}else{
console.log("Current value in range");
pickElement.style.border = '';
pickElement.style.outline = '';
pickElement.style.borderColor = '';
pickElement.style.boxShadow = '';
}
问题
现在,当我输入输入值 49 或 59 时,一切正常 但是 9 是一个错误。这是所有 3 个场景的屏幕截图。
此外,上面代码中的控制台消息输出
The current value in focus is (9) and it's max is (50) 用于控制台 1,并且
Error. Value (9) exceeds max (50) 用于控制台 2。
我可能遗漏了什么或做错了什么?
【问题讨论】:
-
如何启动检查?你能创建一个工作代码sn-p吗?
-
代码是调用 onload 的函数的一部分
标签: javascript validation input user-input