Reputation: 1311
I'm trying to consolidate all the validation values in one function by calling out one php file. It manage to validate but somehow if I validate one field, another field message will also come out.
Form:
<input name="SNo" type="text" id="SNo" onkeyup="Validate(this.value)" value=""/> <span id="validateNumbers"></span>
<input name="Names" type="text" id="Names" onkeyup="Validate(this.value)" value=""/><span id="validateNames"></span>
Javascript function:
function Validate(value) {
var SNo = document.getElementById('SNo').value;
var Names = document.getElementById('Names').value;
if (str == SNo) {
if (str.length == 0) {
document.getElementById("validateNumbers").innerHTML = "Must not be blank";
return;
}
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("validateNumbers").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "functions/validate.php?SNo=" + str, true);
xmlhttp.send();
} else if (str == Names) {
//same coding as if statement
} else {}
}
So if i leave it blank, both validateNumbers and validateNames errors message will appear as well as other messages. I did not use any looping but why it will repeat.. Please advise.
Upvotes: 0
Views: 502
Reputation: 159754
str is not defined. Better to pass in input object itself.
function Validate(field) {
var SNo = document.getElementById('SNo');
var Names = document.getElementById('Names');
if (field == SNo) {
if (field.value.length == 0) {
document.getElementById("validateNumbers").innerHTML = "Must not be blank";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("validateNumbers").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "functions/validate.php?SNo=" + field.value, true);
xmlhttp.send();
} else if (field == Names) {
//same coding as if statement
} else {}
}
and
<input name="SNo" type="text" id="SNo" onkeyup="Validate(this)" value=""/>
<input name="Names" type="text" id="Names" onkeyup="Validate(this)" value=""/>
Upvotes: 1