Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two input fields

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>

like image 527
suva Avatar asked Dec 07 '22 12:12

suva


2 Answers

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).

like image 63
Lemex Avatar answered Dec 24 '22 19:12

Lemex


Here's a suggestion/hint

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

And here's the jsfiddle link, if you want to see the answer

like image 43
su- Avatar answered Dec 24 '22 21:12

su-