Comparing two input fields
html, javascript
Solution
A tidy way to do it which is easy to read:
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
}
This allows you to use the values again after comparison as variables (firstInput), (secondInput).
Problem
I have this function which i am using to compare two input fields. If the user enters the same number in both the text field. On submit there will be an error. Now i would like to know if there is a way to allow same number but not higher than or lower the value of the previous text box by 1. For example if user enters 5 in previous text box, the user can only input either 4, 5 or 6 in the other input field.Please give me some suggestions. ``` <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> ```