javascript - 比较两个输入字段

标签 javascript html

我有这个功能,我用它来比较两个输入字段。如果用户在两个文本字段中输入相同的数字。提交时会报错。现在我想知道是否有办法允许相同的数字但不高于或低于前一个文本框的值 1。例如,如果用户在前一个文本框中输入 5,则用户只能输入 4,其他输入字段中的 5 或 6。请给我一些建议。

   <script type="text/javascript">
function Validate(objForm) {
var arrNames=new Array("text1", "text2");
var arrValues=new Array();
for (var i=0; i<arrNames.length; i++) {
var curValue = objForm.elements[arrNames[i]].value;
if (arrValues[curValue + 2]) {
alert("can't have duplicate!");
return false;
}
arrValues[curValue] = arrNames[i];
}
return true;
}
</script>

<form onsubmit="return Validate(this);">
<input type="text" name="text1" /><input type="text" name="text2" /><button type="submit">Submit</button>
</form>

最佳答案

一种易于阅读的简洁方法:

var firstInput = document.getElementById("first").value;
var secondInput = document.getElementById("second").value;

if (firstInput === secondInput) {
    // do something here if inputs are same
} else if (firstInput > secondInput) {
    // do something if the first input is greater than the second
} else {
    // do something if the first input is less than the second
}

这允许您在比较后再次使用这些值作为变量 (firstInput)、(secondInput)。

关于javascript - 比较两个输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12058081/

相关文章:

javascript - 替换为 RegEx 和 JavaScript

javascript - moment.js 显示错误时间

iphone - 嵌入式视频播放多个方向?

php - 我提供的图片不正确吗,它们都显示为旋转了 90 度

javascript - 为什么orientationchange事件在桌面上不触发?

javascript - 如何在类中正确定义抽象方法,如果未实现抽象方法,IDE 会提示?

javascript - 时间条件句怎么写?

javascript - ng-repeat 内的 AngularJs 表更改值

php - 在元标记中使用换行符

html - overflow hidden 的 z-index