I use the following or similar setup on all my code. I realise that if you skip ALL fields and only enter the last field, no matter what the last field is.. the form submits.. I want to prevent the form submitting if the details (flag is 1)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS</title>
</head>
<body>
<form name="m2mform" id="m2mform" method="post" onsubmit="return form()" >
u:<input id="user" name="user" type="text" value="">
email:<input id="email" name="email" type="text" value="">
<input class="submitx" type="button" onClick="javascript:form();"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
flag = 1;
function form() {
if (document.getElementById("user").value == "") {
// slidedown some red css
flag = 1;
} else {
// dont show red css
flag = 0;
}
if (document.getElementById("email").value == "") {
// slidedown some red css
flag = 1;
} else {
// dont show red css
flag = 0;
}
if (flag == 1) {
// dont submit form
}
else {
var submitForm;
submitForm = document.getElementById("m2mform");
submitForm.submit();
}
}
</script>
</body>
</html>
Updated with another attempt:
var flag = 0;
function nValidateForm() {
var flag = 0;
if (document.getElementById("fullname").value == "") {
$('#fullnamefail').slideDown("fast");
flag = 1;
}
else {
$('#fullnamefail').slideUp("fast");
flag = 0;
}
if (flag == 1) {
$('#error').fadeIn('slow');
return false;
}
else {
var custForm;
custForm = document.getElementById("m2mform");
custForm.submit();
}
}
Your logic is flawed. You must not lower the flag (change to 0) if it’s already raised (equal to 1). In addition, you should not directly call
submit()again, just return true or false.Fix with minimal changes to your original code:
This simply set the flag to 0 only once, on top, and any validation error cause the flag to be raised.
This will work, but as you’re already using jQuery consider using its power.. just Google for “jQuery form validation” for very powerful and simple ways to validate user input.