I have a small form that i want to validate and disable submit button to prevent multiple entries being added to the database.
I just check that Firstname and Lastname are at leat 2 characters and Second disable the button on form submit.
The only problem now is that it doesn't submit the form it just reload the page.
my code is:
function disableButton() {
/*disable button after form submit*/
var imgFirstname = document.getElementById('imgFname');
var imgLastname = document.getElementById('imgLname');
var firstname = document.forms['form']['txtFname'];
var lastname = document.forms['form']['txtLname'];
var errors = 0;
if (firstname.value.length < 2) {
firstname.style.border = "1px solid #f50303";
imgFirstname.src = "images/error.png";
errors++;
} else {
firstname.style.border = "1px solid #06be15";
imgFirstname.src = "images/success.png";
}
if (lastname.value.length < 2) {
lastname.style.border = "1px solid #f50303";
imgLastname.src = "images/error.png";
errors++;
} else {
lastname.style.border = "1px solid #06be15";
imgLastname.src = "images/success.png";
}
firstname.addEventListener('blur', fNameVerify, true);
lastname.addEventListener('blur', lNameVerify, true);
function fNameVerify() {
if (firstname.value.length > 1) {
firstname.style.border = "1px solid #06be15";
imgFirstname.src = "images/success.png";
} else {
firstname.style.border = "1px solid #f50303";
imgFirstname.src = "images/error.png";
}
}
function lNameVerify() {
if (lastname.value.length > 1) {
lastname.style.border = "1px solid #06be15";
imgLastname.src = "images/success.png";
} else {
lastname.style.border = "1px solid #f50303";
imgLastname.src = "images/error.png";
}
}
if (errors == 0) {
// document.getElementById("idBtnAdd").disabled = true;
document.forms["form"].submit();
return true;
} else {
return false;
}
}
<form name='form' onsubmit='return disableButton();' method='post'>
<label for='idFirstname'>First Name:*</label>
<input id='idFirstname' type='text' name='txtFname'>
<img id='imgFname' src='images/transparent.png'>
<label for='idLastname'>Last Name:*</label>
<input id='idLastname' type='text' name='txtLname'>
<img id='imgLname' src='images/transparent.png'>
<label for='idPhone'>Phone (Optional):</label>
<input id='idPhone' type='text' name='telPhone'>
<img id='imgPhone-error' src='images/transparent.png'>
<button id='idBtnAdd' type='submit' name='btnAdd'>Add Client!</button>
</form>
document.forms["form"].submit(), since returningtruewill submit the form.actionattribute in the form, so submitting the form sends to the same URL as the original page, which will just reload it if there's no script there.actionparameter. Do you intend to submit it to the page itself? if so, whats wrong with it?