我有这个功能,我用它来比较两个输入字段。如果用户在两个文本字段中输入相同的数字。提交时会报错。现在我想知道是否有办法允许相同的数字但不高于或低于前一个文本框的值 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/