Validation message doesn't show - javascript

Good day everyone! My problem is why the firstName & lastName error message not showing. The username & password error message is working fine. Even if the password and confirm password error is working fine. The only problem is when my firstName and lastName is empty no error message show. I already download the jQuery and include it to my head tag. I double check the id names if same with my html. I think there are same. Can somebody help me regarding to my problem? I will show you my codes below!
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
if (error_firstname = false && error_lastname = false) {
return true;
} else {
return false;
}
});
});
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>

This line is wrong:
if (error_firstname = false && error_lastname = false)
It's doing assignment, not comparison. Change that if/else to:
return !error_firstnames && !error_lastnames;
$(function() {
$("#firstname_errors").hide(); //hide the span tag
$("#lastname_errors").hide(); //hide the span tag
var error_firstnames = false;
var error_lastnames = false;
$("#form_firstnames").focusout(function() {
check_firstname();
});
$("#form_lastnames").focusout(function() {
check_lastname();
});
function check_firstname() {
var firstname = $("#form_firstnames").val();
if (firstname == "") {
$("#firstname_errors").html("Firstname is empty");
$("#firstname_errors").show();
$("#firstname_errors").addClass("formError");
error_firstnames = true;
} else {
$("#firstname_errors").hide();
}
}
function check_lastname() {
var lastname = $("#form_lastnames").val();
if (lastname == "") {
$("#lastname_errors").html("Lastname is empty");
$("#lastname_errors").show();
$("#lastname_errors").addClass("formError");
error_lastnames = true;
} else {
$("#lastname_errors").hide();
}
}
$("#registration_forms").submit(function() {
error_firstnames = false;
error_lastnames = false;
check_firstname();
check_lastname();
return !error_firstnames && !error_lastnames;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id=registration_forms action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<div>
<label for="fname">First Name: </label>
<input type="text" name="fname" id="form_firstnames" placeholder="First Name" autocomplete="off">
<span id="firstname_errors"></span> //error message
</div>
<div>
<label for="lname">Last Name: </label>
<input type="text" name="lname" id="form_lastnames" placeholder="Last Name" autocomplete="off">
<span id="lastname_errors"></span> //error message
</div>
<div>
<input type="submit" name="btnSave" value="Register">
</div>
Already a member? Login
</form>

Related

javascript is not being called when i try to submit a form

// Staff name validation:
function staffValidation () {
var valid = true;
var staff_name = document.getElementById("staff_name").value;
var validname = /^[a-zA-Z\s]*$/;
error1 = document.getElementById("errorMsg1").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg1").innerHTML = "*STaff name is required";
valid = false;
}
else if (full_name.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg1").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
//email validation:
function emailValidation () {
var valid = true;
var validEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = document.getElementById("email1").value;
error2 = document.getElementById("errorMsg2").innerHTML ="*";
if (email == "" ) {
document.getElementById("errorMsg2").innerHTML = "*Email is required";
valid = false;
}
else if (email.match(validEmail)) {
valid = true;
}
else {
document.getElementById("errorMsg2").innerHTML = "*Please enter a valid email.";
valid =false ;
}
return valid;
}
// Subject validation:
function subjectValidation () {
var valid = true;
var subject = document.getElementById("subject1").value;
var validname = /^[a-zA-Z\s]*$/;
error3 = document.getElementById("errorMsg3").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg3").innerHTML = "*Subject is required";
valid = false;
}
else if (subject.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg3").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
// Problem type validation:
function problemValidation () {
var valid = true;
var prob = document.getElementsByName("problem_type")[0].value;
error4 = document.getElementById("errorMsg4").innerHTML ="*";
if (prob == "") {
document.getElementById("errorMsg4").innerHTML = "*Please select a problem type.";
valid = false;
}
else {
valid = true;
}
return valid;
}
// Description validation:
function descriptionValidation () {
var valid = true;
var description = document.getElementById("description1").value;
error5 = document.getElementById("errorMsg5").innerHTML ="*";
if (description == "" ) {
document.getElementById("errorMsg5").innerHTML = "*Description is required";
valid = false;
}
else if (description.length < 100) {
document.getElementById("errorMsg5").innerHTML = "*Please be more specific, type 100 characters minimum.";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit () {
if ( staffValidation() == false || emailValidation() == false || subjectValidation() == false || problemValidation() == false || descriptionValidation() == false ) {
document.getElementById("errorMsg").innerHTML = "* Please complete the required fields correctly";
return false;
}
else {
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="log-it-reports2.css">
<script src="log-it-reports.js"></script>
<title>WearView Academy Homepage</title>
</head>
<body>
<div class= "content">
<div class="inner-body">
<div class="form1">
<form method="GET" onsubmit=" return formSubmit() " action="#">
<div class="error1" id= "errorMsg"></div>
<div class="error" id= "errorMsg1"></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" name="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2"></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com">
</div><br>
<div class="error" id= "errorMsg3"></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4"></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5"></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Im trying to validate a form using javascript code, however the form action automatically takes place without any validation happening. i would like to know why my javascript code is not being called which i sourced in the head tag with the name "log-it-issues.js", could it be a syntax error ? i tried to scan my code for such an error , but no result, thank you for taking time to look at my code.
The input stuff id isn't set
Give that input an id and the form will work correctly : staff_name
<input class="field" name="staff_name" id="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name">

Why does my JavaScript seems to not run in my HTML

Sorry for any formatting error, first time posting.
Sorry if similar of this is already answered, I couldn't find it anywhere (or I'm just bad at searching).
I'm doing a page to register user to my website, my javascript doesn't work and I can't find what's wrong with it.
My html file does not display the alertbox which supposed to run if I leave my box empty, putting in the wrong characters, etc.
registration.html
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>Registration Form</title>
</head>
<body onLoad="document.registration.userID.focus();">
<h1>Registration Form</h1>
<form name="registration" onSubmit="return validation();">
<label for="userID">User ID</label><br><input id="userID" name="userID" placeholder="Enter your ID" type="text"/><br>
<label for="userPass">Password</label><br><input id="userPass" name="userPass" placeholder="Enter your password" type="password" /><br>
<label for="userName">Username</label><br><input id="userName" name="userName" placeholder="Enter your username" type="text" /><br>
<label for="addr">Address</label><br><input id="addr" name="addr" placeholder="eg. Tamara Residence" type="text" /><br>
<label for="ctry">Country</label><br><select id="ctry" name="ctry">
<option value="DEF">Please select your country</option>
<option value="MY">Malaysia</option>
<option value="IN">India</option></select><br>
<label for="zip">Zip Code</label><br><input id="zip" name="zip" placeholder="eg. 25565" type="text" /><br>
<label for="email">Email</label><br><input id="email" name="email" placeholder="eg. nikfarisaiman109#gmail.com" type="text" /><br>
Sex<br>
<input type="radio" id="1" name="sex" value="1">
<label for="1">Male</label><br>
<input type="radio" id="2" name="sex" value="2">
<label for="2">Female</label><br>
Language<br>
<input type="checkbox" id="EN" name="EN" value="English">
<label for="EN">English</label><br>
<input type="checkbox" id="MY" name="MY" value="Malay">
<label for="MY">Malay</label><br>
<label for="about">About</label><br>
<textarea id="about" name="about" rows="4" cols="50">
</textarea><br><br>
<input name="submit" type="submit" value="Register" />
</form>
<script src="formValidation.js" type="text/javascript"></script>
</body>
</html>
formValidation.js
function validation(){
var userID = document.registration.userid;
var userPass = document.registration.password;
var userName = document.registration.name;
var addr = document.registration.address;
var ctry = document.registration.country;
var zip = document.registration.zip;
var email = document.registration.email;
var sex = document.registration.sex;
if (userID_validate(userID,5,12)) {
if (userPass_validate(userPass,7,12)) {
if (alphabet_validate(userName)) {
if (alphanumeric_validate(addr)) {
if (empty_validate(ctry)) {
if (allnumeric_validate(zip)) {
if (emailformat_validate(email)) {
if (sex_validate(sex)) {
}
}
}
}
}
}
}
}
return false;
}
function userID_validate(userID,a,b) {
//length of string
var userID_length = userID.value.length;
if (userID_length == 0 || userID_length >= a || userID_length < b) {
alert("ID should not be empty / length should be between " + a + " to " + b + " characters");
userID.focus();
return false;
}
return true;
}
function userPass_validate(userPass,a,b) {
//length of string
var userPass_length = userPass.value.length;
if (userPass_length == 0 || userPass_length >= a || userPass_length < b) {
alert("Password should not be empty / length should be between " + a + " to " + b + " characters");
userPass.focus();
return false;
}
}
function alphabet_validate(userName) {
var betReg = /^[A-Za-z]+$/;
if (userName.value.match(betReg)) {
return true;
}
else {
alert("Username should only contain alphabet");
userName.focus();
return false;
}
}
function alphanumeric_validate(addr) {
var betnumReg = /^[0-9A-Za-z]+$/;
if (addr.value.match(betnumReg)) {
return true;
}
else {
alert("Address can only be alphanumeric");
addr.focus();
return false;
}
}
function empty_validate(ctry) {
if(ctry.value == "DEF"){
alert("Please select a country");
ctry.focus();
return false;
}
else
return true;
}
function allnumeric_validate(zip) {
var numReg = /^[0-9]+$/;
if (zip.value.match(numReg)) {
return true;
}
else {
alert("ZIP Code should only contain only numbers");
zip.focus();
return false;
}
}
function emailformat_validate(email) {
var emailReg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if(email.value.match(emailReg))
return true;
else {
alert("Please enter in a correct email address format");
email.focus();
return false;
}
}
function sex_validate(sex) {
var formValid = false;
var x = 0;
while (!formValid && x < document.getElementById("sex").length) {
if (document.getElementById("sex")[x].checked)
formValid = true;
x++;
}
if (!formValid){
alert("Please select male or female");
sex.focus();
return false;
}
else {
alert("Form successfully submitted, thank you for registering!");
window.location.reload();
return true;
}
}
Did you check the error on Console via doing Inspect Element? I copied the same code as you mentioned in Question and getting this error in Console.
Uncaught TypeError: userID is undefined
In your formValidation.js, please update the
var userID = document.registration.userid;
With correct userID as follow.
var userID = document.registration.userID;
Try putting the <script> into <head>

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

Form submits even though it is not passing validation through JavaScript

I'm making a simple form and have made a function for each field to validate. But when I test the form via live server, the form submits even if the fields don't validate. Each function seems to work as intended aside from that.
function validateForm () {
var firstName = document.getElementById('fname').value;
var phoneNumber = document.getElementById('phonenumber').value;
function firstNameValid () {
if (firstName == "") {
console.log("First name empty")
return false;
} else {
return true;
};
};
firstNameValid();
function phoneValid () {
if (phoneNumber == null || phoneNumber == "" || phoneNumber.length < 10) {
console.log("Phone number must be defined and not exceed 10 characters")
return false;
} else {
return true;
}
};
phoneValid();
result = firstNameValid() && phoneValid();
};
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid()"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber" onsubmit="return phoneValid()">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script src="app.js"> </script>
</body>
You're not returning the result variable
result = firstNameValid() && phoneValid();
return result;
You should return the result.
function validateForm() {
var firstName = document.getElementById('fname').value;
var phoneNumber = document.getElementById('phonenumber').value;
function firstNameValid () {
if (firstName == "") {
console.log("First name empty")
return false;
} else {
return true;
};
};
function phoneValid () {
if (phoneNumber == null || phoneNumber == "" || phoneNumber.length < 10) {
console.log("Phone number must be defined and not exceed 10 characters")
return false;
} else {
return true;
}
};
return firstNameValid() && phoneValid();
};
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
</body>

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

Categories