比较两个输入字段

问题描述 投票:3回答:3

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

javascript html
3个回答
9
投票

干净利落的方式是:

var fistInput = 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 grater than the second
} else {
    // do something if the first input is less than the second
}

这允许您在比较后再次使用这些值。


3
投票

这是一个建议/提示

if (Math.abs(v1 - v2) <= 1) {
    alert("can't have duplicate!");
    return false;
}

如果你想看到答案,这里是jsfiddle链接


1
投票

给他们两个ID。

然后使用

if(document.getElementById("first").value == document.getElementById("second").value){
    //they are the same, do stuff for the same
}else if(document.getElementById("first").value >= document.getElementById("second").value
    //first is more than second
}

等等。

© www.soinside.com 2019 - 2024. All rights reserved.