External js file not working with HTML file - javascript

Currently I am building a website which this page uses an external javascript file, one of the main function is that in the form if the user does not enter anything or enter the wrong value and clicks on the submit button, a error message will show up above each section, but unfortunately mine when I click on the submit button it will still submit and will not show any error, I suspect that the Javascript file is not linked properly but I did set the path correctly as you can see in the picture and the on the HTML page.
HTML File:
<meta charset="utf-8" />
<meta name="description" content="Demonstrates some basic HTML content elements and CSS" />
<meta name="keywords" content="html, css" />
<meta name="author" content="Jordan Siow" />
<link rel = "stylesheet" type = "text/css" href = "styles/style.css"/>
<script type="text/JavaScript" src="scripts/apply.js"></script>
<title>Apply </title>
<section class="front_title">
<p> Company XIT <img src="styles/images/logo.png" alt="logo" height="70" width="250"/>
</p>
</section>
<section class="topnav">
<table>
<tr>
<td >
Main
</td>
<td >
Jobs
</td>
<td id="current">
Apply
</td>
<td>
About
</td>
<td>
Enhancements
</td>
</tr>
</table>
</section>
<section id="style_apply">
<h2>Submit your Application!</h2>
<form method="post" id="apply_form" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p><span id="job_id_error" class="error"></span></p>
<p><label for="jobid">Job Reference Number</label>
<input type="text" name="jobid" id="jobid" maxlength="5" pattern="[0-9]{5}" /></p>
<p><span id="firstname_error" class="error"></span></p>
<p><label for="firstname">First Name</label>
<input type ="text" name="First Name" id="firstname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<p><span id="lastname_error" class="error"></span></p>
<p><label for="lastname">Last Name</label>
<input type ="text" name="Last Name" id="lastname" maxlength="20" pattern="[a-zA-Z]+" /></p>
<br/>
<p><span id="dob_error" class="error"></span></p>
<p><label for="dateofbirth">Date of Birth</label>
<input type="date" name="Date of Birth" id="dateofbirth" /></p>
<br/>
<br/>
<label>Gender</label>
<p><span id="gender_error" class="error"></span></p>
<fieldset id="gender">
<label for="male">Male</label>
<input type="radio" id="male" name="Gender" value="male" />
<label for="female">Female</label>
<input type="radio" id="female" name="Gender" value="female"/>
<label for="other">Others</label>
<input type="radio" id="other" name="Gender" value="other"/>
<label for="rathernotsay">Rather Not Say</label>
<input type="radio" id="rathernotsay" name="Gender" value="rathernotsay"/>
</fieldset>
<br/>
<div id="fieldset_label">
<label>Address Information</label>
</div>
<fieldset>
<p><span id="streetaddress_error" class="error"></span></p>
<p><label for="streetaddress">Street address</label>
<input type="text" name="Address" id="streetaddress" maxlength="40" "/></p>
<p><span id="suburb_error" class="error"></span></p>
<p><label for="suburb">Suburb/town</label>
<input type="text" name= "Suburb" id="suburb" maxlength="40" /></p>
<p><span id="state_error" class="error"></span></p>
<p><label for="state">State</label>
<select id="state" name="State">
<option value="">Please select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select></p>
<p><span id="postcodr_error" class="error"></span></p>
<p><label for="postcode">Postcode</label>
<input type="text" name= "Postcode" id="postcode" maxlength="4" pattern="\d{4}" placeholder="Postcode"/></p>
</fieldset>
<br/>
<p><span id="email_error" class="error"></span></p>
<p><label for="email">Email</label>
<input type="text" name="Email Address" id="email" /></p>
<p><span id="phonenumber_error" class="error"></span></p>
<p><label for="phonenumber">Phone Number</label>
<input type="text" name="Phone Number" id="phonenumber" maxlength="12" pattern="[0-9]{8-12}" ></p>
<label>Skill list</label>
<fieldset>
<p><span id="skill_error" class="error"></span></p>
<label for="skill1">Web development languages</label>
<input type="checkbox" id="skill1" name="Skill 1" value="skill"/>
<label for="skill2">Data Management abilities</label>
<input type="checkbox" id="skill2" name="Skill 2" value="skill"/>
<label for="skill3">Others</label>
<input type="checkbox" id="skill3" name="Other" value="skill"/>
<br/>
<br/>
<section>
<label for="comm" style="display:block">Other skillset</label>
<textarea class="comments" id="comm" name="Comments" rows="5" cols="50" placeholder="Other skillsets..."></textarea>
</section>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/>
<div class="align_center">
<p><span id="error_check" class="error"></span></p>
<input type="submit" value="Submit Application"/>
<input type="reset" value="Reset Application form"/>
</div>
</form>
</section>
<br/>
<br/>
<br/>
<br/>
<footer class = "footer_text">
<hr/>
<p>
<strong>©</strong>
<a class="footer_text" href="http://www.swinburne.edu.au/">
Swinburne Universty of Technology
</a>
</p>
<p>  
 
<strong>Done by:</strong> <a class="footer_text" href="mailto:103173691#student.swin.edu.au">
Jordan Siow</a>
</p>
</footer>
JS File:
/* To Validate the Form */
function validate(){
// Initialises the result variable
var result = true;
// Intialises the error tags
var job_id_error = document.getElementById("job_id_error");
job_id_error.innerHTML = "";
var firstname_error = document.getElementById("firstname_error");
firstname_error.innerHTML = "";
var lastname_error = document.getElementById("lastname_error");
lastname_error.innerHTML = "";
var dob_error = document.getElementById("dob_error");
dob_error.innerHTML = "";
var gender_error = document.getElementById("gender_error");
gender_error.innerHTML = "";
var streetaddress_error = document.getElementById("streetaddress_error");
streetaddress_error.innerHTML = "";
var suburb_error = document.getElementById("suburb_error");
suburb_error.innerHTML = "";
var state_error = document.getElementById("state_error");
state_error.innerHTML = "";
var postcode_error = document.getElementById("postcode_error");
postcode_error.innerHTML = "";
var email_error = document.getElementById("email_error");
email_error.innerHTML = "";
var phonenumber_error = document.getElementById("phonenumber_error");
phonenumber_error.innerHTML = "";
var skill_error = document.getElementById("skill_error");
skill_error.innerHTML = ""
// If there is an error in the input it will set the result to false and displays an error message
// To get the variables from the form and will chgeck the given rules
var jobid = document.getElementById("jobid").value;
if (jobid == ""){
job_id_error.innerHTML = "Job Reference Number must not be blank";
result = false;
}
var firstname = document.getElementById("firstname").value;
if (!firstname.match(/^[a-zA-Z]+$/) || firstname.value == ""){
firstname_error.innerHTML = "First name must only contain alphabetic characters";
alert("First name must only contain alphabetic characters")
result = false;
}
var lastname = document.getElementById("lastname").value;
if (!lastname.match(/^[a-zA-Z\-]+$/) || lastname.value == ""){
lastname_error.innerHTML = "Last name must only contain aphabetic characters";
result = false;
}
var dateofbirth = document.getElementById("dateofbirth").value;
if (!dateofbirth.match(/\d{2}\/\d{2}\/\d{4}/)){
dob_error.innerHTML = "Invalid Date of Birth";
result = false;
}
var age = calculate_age(dateofbirth);
if (!isFinite(age) || isNaN(age)) {
dob_error.innerHTML = "Your Date of Birth role is not Available.";
result = false;
}
else if (age < 21 || age > 70) {
dob_error.innerHTML =
"You must be between 21 and 70 years old to apply.";
result = false;
}
var male = document.getElementById("male").checked;
var female = document.getElementById("female").checked;
var other = document.getElementById("other").checked;
var rathernotsay = document.getElementById("rathernotsay").checked;
if (!(male || female || other || rathernotsay)) {
gender_error.innerHTML = "Please select a gender.";
result = false;
}
var streetaddress = document.getElementById("streetaddress").value;
if (streetaddress == "") {
streetaddress_error.innerHTML = "You must enter a street address.";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (suburb == "") {
suburb_error.innerHTML = "You must enter a suburb or town";
result = false;
}
var postcode = Number(document.getElementById("postcode").value);
if (postcode == "") {
postcode_error.innerHTML = "You must select a postcode";
result = false;
}
var state = document.getElementById("state").value
if (state == "") {
state_error.innerHTML = "You must select a state";
result = false;
} else {
var tempMsg = validate_postcode(state, postcode);
if (tempMsg != "") {
state_error.innerHTML = tempMsg;
result = false;
}
}
var email = document.getElementById("email").value;
if (email == "") {
email_error.innerHTML = "You must enter an email address";
result = false;
}
var phonenumber = document.getElementById("phonenumber").value;
if (phonenumber == "") {
phonenumber_error.innerHTML = "You must enter a phone number";
result = false;
}
if (result){
storeBooking(firstname, lastname, dateofbirth, male, female, other, rathernotsay, streetaddress, suburb, state, postcode, email, phonnumber)
}
if (!result) {
document.getElementById("error_check").innerHTML = "Please correct all of the errors given above.";
}
return result;
}
/**
* calcualte age from date of birth
*/
function calculate_age(dateofbirth) {
var today = new Date();
var DateOfBirth = new Date(dateofbirth);
// get the difference between the years
var age = today.getFullYear() - DateOfBirth.getFullYear();
// get the difference between the months
var month = today.getMonth() - DateOfBirth.getMonth();
// if the dateofbirth month and day is earlier in the year
if (month < 0 || (month === 0 && today.getDate() < DateOfBirth.getDate())) {
age--; // remove a year
}
return age;
}
function validate_postcode(state, postcode) {
var errMsg = "";
switch (state) {
case "vic":
if (!((postcode >= 3000 && postcode <= 3999) || (postcode >= 8000 && postcode <= 8999))) {
errMsg += "Post Code not in Victoria.";
}
break;
case "nsw":
if (!((postcode >= 1000 && postcode <= 2599) || (postcode >= 2619 && postcode <= 2899) || (postcode >= 2921 && postcode <= 2999))) {
errMsg += "Post Code not in New South Wales.";
}
break;
case "qld":
if (!((postcode >= 4000 && postcode <= 4999) || (postcode >= 9000 && postcode <= 9999))) {
errMsg += "Post Code not in Queensland.";
}
break;
case "nt":
if (!(postcode >= 800 && postcode <= 999)) {
errMsg += "Post Code not in Northern Territory.";
}
break;
case "wa":
if (!(postcode >= 6000 && postcode <= 6999)) {
errMsg += "Post Code not in Western Australia.";
}
break;
case "sa":
if (!(postcode >= 5000 && postcode <= 5999)) {
errMsg += "Post Code not in Southern Australia.";
}
break;
case "tas":
if (!(postcode >= 7000 && postcode <= 7999)) {
errMsg += "Post Code not in Tasmania.";
}
break;
case "act":
if (!((postcode >= 200 && postcode <= 299) || (postcode >= 2600 && postcode <= 2618) || (postcode >= 2900 && postcode <= 2920))) {
errMsg += "Post Code not in Australian Capital Territory.";
}
break;
default:
errMsg = "Post Code not Valid.";
}
return errMsg;
}
/**
* Prefill the form from exisitng session data
*/
function prefill_id() {
var jobId_input = document.getElementById("jobid");
if (localStorage.jobId != undefined) {
// hidden input to submit details
jobId_input.value = localStorage.jobId;
jobId_input.readOnly = true;
} else {
jobId_input.readOnly = false;
}
}
/**
* Prefill the form from exisitng session data
*/
function prefill_form() {
prefill_id();
if (sessionStorage.firstname != undefined) {
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("dateofbirth").value = sessionStorage.dateofbirth;
document.getElementById("streetaddress").value = sessionStorage.streetaddress;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("phonenumber").value = sessionStorage.phonenumber;
switch (sessionStorage.gender) {
case "male":
document.getElementById("male").checked = true;
break;
case "female":
document.getElementById("female").checked = true;
break;
case "other":
document.getElementById("other").checked = true;
break;
case "rathernotsay":
document.getElementById("rathernotsay").checked = true;
break;
}
var skills = sessionStorage.skills;
document.getElementById("skill1").checked = skills.includes("skill1");
document.getElementById("skill2").checked = skills.includes("skill2");
document.getElementById("skill3").checked = skills.includes("skill3");
}
}
/**
* Store Job ID for pre fill in application form
*/
function storeJobId1() {
localStorage.jobId = document.getElementById("job1_id").innerHTML;
}
function storeJobId2() {
localStorage.jobId = document.getElementById("job2_id").innerHTML;
}
/**
* Store values for session
*/
function storeBooking(skill1, skill2, skill3, comm, firstname,
lastname, dateofbirth, streetaddress, suburb, state, postcode, email, phonenumber, male, female, other) {
// store values in sessionStorage
var skill_string = "";
if (skill1) {
skill_string = "skill1";
}
if (skill2) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill2";
}
if (skill3) {
if (skill_string != "") {
skill_string += ", ";
}
skill_string += "skill3";
}
sessionStorage.skills = skill_string;
sessionStorage.firstname = firstname;
sessionStorage.lastname = lastname;
sessionStorage.dateofbirth = dateofbirth;
sessionStorage.streetaddress = streetaddress;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = ;
sessionStorage.email = email;
sessionStorage.phonenumber = phonenumber;
sessionStorage.comm = comm;
if (male) {
sessionStorage.gender = "male";
} else if (female) {
sessionStorage.gender = "female";
} else if (other) {
sessionStorage.gender = "other";
} else if (rathernotsay) {
sessionStorage.gender = "rathernotsay";
}
}
/*
This function is called when the browser window loads
it will register functions that will respond to browser events
*/
function init() {
if (document.title == "Available Jobs") {
document.getElementById("job1_apply").onclick = storeJobId1;
document.getElementById("job2_apply").onclick = storeJobId2;
} else if (document.title == "Application Form") {
prefill_form();
// register the event listener to the form
document.getElementById("apply_form").onsubmit = validate;
document.getElementById("apply_form").onreset = function () {
localStorage.clear();
prefill_id();
;}
}
}
window.onload = init;

I think you should check out this article: preventDefault() Event Method
When clicked, you should prevent the default behavior.

<script type="text/JavaScript" src="scripts/apply.js"></script>
Add the above script tag just before closing of body tag, it it best practice.
put a console.log("js file linked"); inside js file to test whether its linked or not.
Feel free to ask if it didn't work...

In the comments you mentioned
my friend told me its got to do with the last line in the js file "window.onload = init();
Your friend is correct - not sure if this is the only relevant thing, but here you are first running the function init() and the return value of that function is being saved into window.onload. Check out this example code:
function init() {
console.log(document.readyState);
}
window.onload = init();
console.log("Window onload is", window.onload);
Here init is run immediately and the return value of init will be saved to window.onload. This prints
loading
apply.js:315 Window onload is null
Instead, you should add a reference to the init function, so that the value of window.onload is your init function itself, not the return value; so the correction would be
function init() {
console.log(document.readyState);
}
window.onload = init;
console.log("Window onload is", window.onload);
// this one prints out
// Window onload is ƒ init() {console.log(document.readyState);}
// apply.js:311 complete
The "document.readyState" is used to check if the document has been loaded and parsed.

Related

Form Submission failed

I have an issue while submitting a form its giving me error that >validateform()is not defined
before it was working.
It is loan application in which I have to send an email once user submit form with correct details and also generate random 4 digit no which will be in email which user will receive
<script src="https://smtpjs.com/v3/smtp.js">
## Heading ##
function validateForm() {
let name = document.forms["myForm"]["fullName"].value;
let email = document.forms["myForm"]["email"].value;
let pan = document.forms["myForm"]["pan"].value;
let lamount = document.forms["myForm"]["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
const mybtn = document.getElementById('btn');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
let number1 = num1.innerText;
let number2 = num2.innerText;
enter code here
mybtn.addEventListener("click", () => {
//
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res == sum_result) {
alert("correct");
}
else {
alert("Incorrect")
}
window.location.reload();
});
if (name == "" || regName.test(name)) {
alert("Name must be filled out");
return false;
}
if (email == "" || !regEmail.test(email)) {
alert("Please enter a valid e-mail address.");
return false;
}
if (pan == "" || !regPan.test(pan)) {
alert("Please enter a valid PAN no.");
return false;
}
//OTP generation
const generateOtp = () =>{
let otp = "";
for(let i=0 ; i < 4 ; i++){
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
console.log("OTP:", generateOtp());
}
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "....",
// To: document.getElementById("email").value,
// From: "....#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
</script>
</head>
<body>
<div class="form-container">
<h1>Loan Application Form</h1>
<form name="myForm" method="post" action="thankyou.html" onsubmit="validateForm();">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span
class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span
class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span
class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span
class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>
You have many issues
You do not have a closing </script> for your <script src="https://smtpjs.com/v3/smtp.js"> and a starting <script> for your code.
Please try to use the snippet editor [<>] and remove the "enter code here" and ## Heading ##
You need to use the submit event and e.preventDefault is stopping the submit. I changed name="myForm" to id="myForm", forms do not need names
You are adding event listeners in the validation.
You were missing the refresh function
Here is what I believe you need
const generateOtp = () => {
let otp = "";
for (let i = 0; i < 4; i++) {
otp += Math.floor(Math.random() * 10);
}
//if we write return otp directly then this will return otp in string
return Number(otp); //this will return otp as number.
};
document.getElementById('bttn').addEventListener("click", e => {
e.preventDefault();
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
//returns a random integer from 0to9
num1.innerText = Math.floor(Math.random() * 10);
num2.innerText = Math.floor(Math.random() * 10);
})
document.getElementById("myForm").addEventListener("submit", (e) => {
const form = e.target;
let name = form["fullName"].value;
let email = form["email"].value;
let pan = form["pan"].value;
let lamount = form["flamnt"].value;
let regName = /\d+$/g;
let regEmail = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
let regPan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//captcha validation
let input_val = document.getElementById('input_val');
let num1 = document.getElementById('num1');
let num2 = document.getElementById('num2');
let number1 = num1.innerText;
let number2 = num2.innerText;
let errors = [];
let sum_result = parseInt(number1) + parseInt(number2);
let res = parseInt(input_val.value);
if (res != sum_result) errors.push("Sum not correct");
if (name == "" || regName.test(name)) errors.push("Name must be filled out");
if (email == "" || !regEmail.test(email)) errors.push("Please enter a valid e-mail address.");
if (pan == "" || !regPan.test(pan)) errors.push("Please enter a valid PAN no.");
if (errors) {
alert(errors.join("\n"));
e.preventDefault();
return
}
//OTP generation
console.log("OTP:", generateOtp()); // not sure what you want with this
// sendEmail()
})
//sending an email
// function sendEmail() {
// Email.send({
// Host: "smtp.gmail.com",
// Username: "...#gmail.com",
// Password: "...",
// To: document.getElementById("email").value,
// From: "...#gmail.com",
// Subject: "Thank you for Inquiry",
// Body: "Well that was easy!!",
// })
// .then(function (message) {
// alert("mail sent successfully")
// });
// }
<script src="https://smtpjs.com/v3/smtp.js"></script>
<div class="form-container">
<h1>Loan Application Form</h1>
<form id="myForm" method="post" action="thankyou.html">
<div class="formdesign" id="name">
Full Name:<input type="text" class="form-control" placeholder="Enter your fullname" name="fullName"><span class="formerror"></span>
</div>
<div class="formdesign" id="email">
Email:<input type="email" class="form-control" placeholder="Enter email" name="email"><span class="formerror"></span>
</div>
<div class="formdesign" id="panno">
PAN No:<input type="text" class="form-control" placeholder="Like BBHPM5672K" name="pan" maxlength="10"><span class="formerror"></span>
</div>
<div class="formdesign" id="lamount">
Loan Amount:<input type="number" class="form-control" placeholder="Enter loan amount" name="flamnt"><span class="formerror"></span>
</div>
<div class="formdesign">
Enter Captcha:<input type="text" placeholder="enter captcha" class="form-control" id="input_val" />
<p id="operation"><span id="num1">1</span> + <span id="num2">2</span></p>
<button id="bttn" class="captcha-refresh"><i class="fa fa-refresh"></i>Refresh</button>
</div>
<input id="btn" class="button" type="submit" value="Submit">
<input class="button" type="reset" value="Reset">
</form>

Javascript and HTML: doesnt show validation alert message upon clicking submit

I have problem with coding html and js. the alert is not appearing upon submitting and i was following the template entirely. Anyone are able to find what is the problem? im sure my script file is in the same directory and the file is linked after i had tested by using document.write(""). And also what i wish the web page to do is to alert(gErrorMsg).
This is the html part
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="" validate="novalidate">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>
this is the Javascript part
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent;
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList;
}
return selected;
}
This is your issue: you're using some undefined variables. Double check your HTML or if the variable is initialized.
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n" + unitList; // ERROR: unitList is undefined
}
return selected;
}
Working Demo
var gErrorMsg = "";
function init() {
var regForm = document.getElementById("regForm");
regForm.onsubmit = validateForm;
}
window.onload = init;
function validateForm(e){
e.preventDefault(); // Necessary for some reason...
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var tutorOK = chkTutor();
var dobOK = isDobOK();
var unitOK = isUnitSelected();
var issueOK = isIssueSelected();
if (nameOK && emailOK && issueOK && dobOK && tutorOK && unitOK){
isAllOK = true;
}
else{
alert(gErrorMsg); //display concatenated error messages
gErrorMsg = ""; //reset error msg
isAllOK = false;
}
return isAllOK;
}
// check name valid format
// demo: nested single branch if statements
// demo: string property and regular expression pattern
function chkName () {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/ //check only alpha characters or space
var nameOk = true;
if (name==""){
gErrorMsg = gErrorMsg + "Your name cannot be blank\n"
nameOk = false; //if condition or clause complex more readable if branches on separate lines
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
//check the pattern of email(regular expression)
// demo: two branch if statement with then
function chkEmail () {
var email = document.getElementById("fmail").value;
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkTutor(){
var selected = false;
var tutor = document.getElementById("tutor").value;
if (tutor!="none"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your tutor\n"
}
return selected;
}
//demo String and Date methods
//demo array index
//check date format is (sort of) ok
// check cat is born and less than 20 yo.
function isDobOK(){
var validDOB = true; //set to false if not ok
var now = new Date(); //current date-time
var dob = document.getElementById("fdob").value;
var dateMsg = "";
//assume format dd/mm/yyyy
var dmy = dob.split("/"); //split date into array with elements dd mm yyy
var allNumbers = true;
for (var i = 0; i < dmy.length; i++){
if(isNaN(dmy[i])){
dateMsg = dateMsg + "You must enter only numbers into the date" + "\n";
validDOB = false;
}
}
if ((dmy[0] <1) || (dmy[0] > 31)){ //day
dateMsg = dateMsg + "Day must be between 1 and 31" + "\n";
validDOB = false;
}
if ((dmy[1] <1) || (dmy[1] > 12)){ //month
dateMsg = dateMsg + "Month must be between 1 and 12" + "\n";
validDOB = false;
}
if ((dmy[2] < now.getFullYear() - 60)) { //dmy[2] = year
dateMsg = dateMsg + "Invalid DOB, you are too old to register" + "\n";
validDOB = false;
}
if (dmy[2] > now.getFullYear()){
dateMsg = dateMsg + "Invalid DOB, you are not born yet." + "\n";
validDOB = false;
}
if (!validDOB){
gErrorMsg = gErrorMsg + dateMsg;
}
return validDOB;
}
//check male or female has been selected
function isUnitSelected(){
var selected = false;
var is11 = document.getElementById("COS10011").checked;
var is04 = document.getElementById("COS60004").checked;
var is07 = document.getElementById("COS60007").checked;
if (is11 || is04 || is07)
selected = true; //we haven't used {}. BE CAREFUL about adding extra lines
else{
selected = false;
gErrorMsg = gErrorMsg + "Please select your unit\n"
}
return selected;
}
//demo counted for loop
/* Use parallel arrays of label and input to check at least one check box is selected
then construct an error message from the labels on the web page
Note: more checkboxes can be added to the html without affecting the JS code
*/
function isIssueSelected(){
var selected = false;
var issue = document.getElementById("issue").getElementsByTagName("input");
var labels = document.getElementById("issue").getElementsByTagName("label");
var label = "";
var issueList = "";
for (var i=0; i < issue.length; i++){
selected = selected || issue[i].checked;
label = ""; //labels[i].firstChild.textContent; // ERROR: labels[i] is undefined
issueList = issueList + "- " + label + "\n";
}
if (!selected){
gErrorMsg = gErrorMsg + "You must select any of the following issue:\n"; // + unitList; // ERROR: unitList is undefined
}
return selected;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./styles/style1.css">
<script src="script.js"></script>
</head>
<body>
<header>
<img id="images" src = "Logo.png" alt="Photo of Logo"/>
</header>
<nav>
<ul>
<li>Contact Us |</li>
<li>Jobs at Swinburne |</li>
<li>Copyright and disclaimer |</li>
<li>Privacy |</li>
<li>Accesibility |</li>
<li>Feedback |</li>
<li>Register</li>
</ul>
</nav>
<form id="regForm" method="post" action="">
<fieldset>
<legend>Personal Details:</legend>
<label for="fname">Name:</label><input type="text" id="fname" name="fname" placeholder="Your name" required="required"/>*<br/>
<label for="fmail">Email:</label><input type="text" id="fmail" name="fmail" placeholder="Your email" required="required"/>*<br/>
<label for="fdob">Date of birth:</label><input type="text" id="fdob" name="fdob" placeholder="dd/mm/yy"/>
</fieldset>
<fieldset>
<legend>Your unit</legend>
<input type="radio" value="cos10011" name="radio" id="COS10011" />COS10011
<input type="radio" value="cos60004" name="radio" id="COS60004" />COS60004
<input type="radio" value="cos60007" name="radio" id="COS60007" />COS60007<br/>
<label for="tutor">Your Tutor:</label>
<select name="tutor" id="tutor">
<option value="none">-------</option>
<option value="t1">Tutor 1</option>
<option value="t2">Tutor 2</option>
<option value="t3">Tutor 3</option>
<option value="other">Other</option>
</select>
</fieldset>
<fieldset id="issue">
<legend >Issue</legend>
<input type="checkbox" name="html" value="html"/>HTML
<input type="checkbox" name="css" value="css"/>CSS
<input type="checkbox" name="javascript" value="jss"/>JavaScript
<input type="checkbox" name="php" value="php"/>PHP
<input type="checkbox" name="mysql" value="sql"/>MySQL
<br/><br/>
<label for="comments">Description of Issue</label><br/>
<textarea name="comments" id="comments" rows="5" cols="20" placeholder="Enter comments header"></textarea>
</fieldset>
<fieldset>
<legend>Preferred Date/Time</legend>
<label for="date">Date:</label>
<input type="date" id="date" name="date"/><br/>
<label for="time">Time:</label>
<input type="time" id="time" name="time"/>
</fieldset>
<input type= "submit" value="Register"/>
<input type= "reset" value="Reset"/>
</form>
</body>
</html>

JavaScript: why did my form validation that runs onsubmit stop working when data transfer between pages is used?

my form validation codes work just fine when I'm not using .getitem and setitem to pass data from other pages to my enquiry page. I kinda know what the problem but my knowledge is so shallow that I can't comprehend and also don't know how to fix it. Anyone knows what to do bout this?
This is the 1st HTML file for product page (Relevant codes):
<button class="enqbutton margin-l50 margin-t50-b50 font-josefin" onclick="storeitem('Enclosed Space Sanitisation: Home')">Enquire</button>
this is the enquiry page:
<!-- enquiry form -->
<form id="detail" method="post" class="font-josefin" action="mailto:101231212#students.swinburne.edu.my" novalidate="novalidate" onsubmit="return validateForm()">
<fieldset>
<legend>Personal Details</legend>
<label class= 'margin-l50' for="fname">Name:</label><br/>
<input class= 'margin-l50' type="text" id="fname" name="fname" placeholder="Your name" size="50" maxlength="30" required="required"/>*<br/>
<label class= 'margin-l50' for="fmail">Email:</label><br/>
<input class= 'margin-l50' type="email" id="fmail" name="fmail" placeholder="Your email" size="50" maxlength="30" required="required"/>*<br/>
<label class= 'margin-l50' for="fhp">Personal Phone Number:</label><br/>
<input class= 'margin-l50' type="tel" id="fhp" name="fhp" placeholder="###-#######" size="50" required="required"/>*
</fieldset>
<fieldset>
<legend>Address</legend>
<label class= 'margin-l50' for="stname">Street Name:</label><br/>
<input class= 'margin-l50' type="text" id="stname" name="stname" placeholder="Street" size="50" maxlength="40" required="required"/>*<br/>
<label class= 'margin-l50' for="city">City/Town:</label><br/>
<input class= 'margin-l50' type="text" id="city" name="city" placeholder="City/Town" size="50" maxlength="20" required="required"/>*<br/>
<label class= 'margin-l50'>State:</label><br/>
<select class= 'margin-l50' name="state" id="statedrop">
<optgroup label="States">
<script>statelist()</script>
</optgroup>
</select>*<br/><br/>
<label class= 'margin-l50' for="fhp">Postcode:</label><br/>
<input class= 'margin-l50' type="text" id="postcode" name="postcode" placeholder="#####" size="50" required="required"/>*
</fieldset>
<fieldset>
<legend>Enquiries</legend>
<label class= 'margin-l50' for="subject" id="subjectLabel">Subject Enquiry On:</label><br/>
<input class= 'margin-l50' type="text" name="subject" id="subject" size="40" /><br/>
<label class= 'margin-l50'>Your queries:</label><br/>
<label class= 'margin-l50'>Service Categories:</label><br/>
<select class= 'margin-l50' name="query" id="servicedrop" onchange="change()">
<optgroup label="Services">
<script>serviceList()</script>
</optgroup>
</select>*<br/><br/>
<label class= 'margin-l50'>Description of your queries</label><br/>
<textarea class= 'margin-l50' id="description" name="description" rows="5" cols="50" placeholder="Enter your queries"></textarea>
</fieldset>
<fieldset>
<legend>Making Appointment</legend>
<label class= 'margin-l50' for="date">Date:</label>
<input class= 'margin-l50' type="date" id="date" name="date"/><br/>
<label class= 'margin-l50' for="time">Time:</label>
<input class= 'margin-l50' type="time" id="time" name="time"/><br/><br/>
<p class= 'margin-l50'>Our team will contact you within 1 business day upon booking to confirm the following booking.</p><br/>
</fieldset>
<div class="button_container">
<button type="submit" class="enqbutton font-josefin" value="Submit">Submit</button>
<button type="reset" class="enqbutton font-josefin" value="Reset">Reset</button>
</div>
</form>
This is the javascript file
var gErrorMsg = "";
function init() {
displayitem();
}
function validateForm(){
"use strict"; //directive to ensure variables are declared
var isAllOK = false;
gErrorMsg = ""; //reset error message
var nameOK = chkName();
var emailOK = chkEmail();
var hpOk = chkHp();
var stOk = chkSt();
var cityOk = chkCt();
var stateOk = chkState();
var postOk = chkPost();
var subOk = chkSubject();
var selectOk = chkSelect();
if (nameOK && emailOK && hpOk && stOk && cityOk && stateOk && postOk && selectOk){
isAllOK = true;
}
else{
alert(gErrorMsg);
gErrorMsg = "";
isAllOK = false;
}
return isAllOK;
}
function chkName() {
var name = document.getElementById("fname").value;
var pattern = /^[a-zA-Z ]+$/
var nameOk = true;
if ((name.length == 0)){
gErrorMsg = gErrorMsg + "Please enter your name\n"
nameOk = false;
}
else if ((name.length > 25)){
gErrorMsg = gErrorMsg + "Input name must be within 25 characters.\n"
nameOk = false;
}
else{
if (!pattern.test(name)){
gErrorMsg = gErrorMsg + "Your name must only contain alpha characters\n"
nameOk = false;
}
}
return nameOk;
}
function chkEmail() {
var email = document.getElementById("fmail");
var result = false;
var pattern = /[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-za-zA-Z0-9.-]{1,4}$/;
if (pattern.test(email.value)){
result = true;
}
else{ //braces a good idea even if not strictly needed for single statement
result = false;
gErrorMsg = gErrorMsg + "Enter a valid email address\n"
}
return result;
}
function chkHp(){
var hp = document.getElementById("fhp").value;
var result = true;
var pattern = /^(\+?6?01)[0|1|2|3|4|6|7|8|9]\-*[0-9]{7,8}$/;
if (pattern.test(hp)){
result = true;
}
else{
result = false;
gErrorMsg = gErrorMsg + "Enter a valid Malaysian phone numbers (11 numerical digits allowed for numbers with '011' prefix) \n"
}
return result;
}
function chkSt() {
var street = document.getElementById("stname").value;
var pattern = /^[a-zA-Z ]+$/
var stOk = true;
if ((street.length == 0)){
gErrorMsg = gErrorMsg + "You must enter the name of the street of your living place\n"
stOk = false;
}
else if ((street.length > 20)){
gErrorMsg = gErrorMsg + "Input street name must be within 20 characters\n"
stOk = false;
}
else{
if (!pattern.test(street)){
gErrorMsg = gErrorMsg + "Street name must only contain alpha characters\n"
stOk = false;
}
}
return stOk;
}
function chkCt() {
var city = document.getElementById("city").value;
var pattern = /^[a-zA-Z ]+$/
var cityOk = true;
if ((city.length == 0)){
gErrorMsg = gErrorMsg + "You must enter the city of your living place\n"
cityOk = false;
}
else if ((city.length > 15)){
gErrorMsg = gErrorMsg + "Input city name must be within 15 characters\n"
cityOk = false;
}
else{
if (!pattern.test(city)){
gErrorMsg = gErrorMsg + "City name must only contain alpha characters\n"
cityOk = false;
}
}
return cityOk;
}
function chkState(){
var selected = false;
var state = document.getElementById("statedrop").value;
if (state!="------"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select your state\n"
}
return selected;
}
function chkPost (){
var post = document.getElementById("postcode").value;
var result = true;
var pattern = /^[0-9]{5}$/;
if (pattern.test(post)){
result = true;
}
else{
result = false;
gErrorMsg = gErrorMsg + "Enter a valid Malaysian postcode with only 5 numerical digits\n"
}
return result;
}
function chkSubject() {
var sub = document.getElementById("subject").value;
var pattern = /^[a-zA-Z ]+$/
var subOk = true;
if ((sub.length == 0)){
gErrorMsg = gErrorMsg + "Subject is empty, must select category and service to enquiry on\n"
nameOk = false;
}
return nameOk;
}
function chkSelect(){
var selected = false;
var ser = document.getElementById("servicedrop").value;
if (ser!="Select a category and service"){
selected = true;
}
else{
selected = false;
gErrorMsg = gErrorMsg + "You must select a category and service for your enquiry\n"
}
return selected;
}
// Array
function serviceList() {
var select = document.getElementById("servicedrop");
var options = [
"Select a category and service",
"Enclosed Space Sanitisation: Home",
"Enclosed Space Sanitisation: Office",
"Enclosed Space Sanitisation: Inventory",
"Enclosed Space Sanitisation: Sport Facilities",
"Event Hygiene Management: Funeral",
"Event Hygiene Management: Sports Event",
"Event Hygiene Management: Gatherings",
"Event Hygiene Management: Exhibitions",
"Wide Area Sanitisation: Hosuing Area",
"Wide Area Sanitisation: Shopping Complex",
"Wide Area Sanitisation: School Area",
"Wide Area Sanitisation: Food Court",
"Object Disinfection: Vehicle",
"Object Disinfection: Luggage",
"Object Disinfection: Walkthorugh Sanitisation",
"Object Disinfection: Professional Gears"
];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function statelist() {
var select = document.getElementById("statedrop");
var options = ["------", "Johor", "Kedah", "Kelantan", "Kuala Lumpur", "Labuan", "Malacca", "Negeri Sembilan", "Pahang", "Perak", "Perlis", "Penang", "Sabah", "Sarawak", "Selangor", "Terengganu"];
for (var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
function makeAnchor() {
var div = document.createElement('div');
var options = ['ENCLOSED SPACE SANITISATION','EVENT HYGIENE MANAGEMENT', 'WIDE AREA SANITISATION', 'OBJECT DISINFECTION'];
for(var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var opt = options[i]
a.href = "./service" + (i + 1) + ".html"
a.appendChild(document.createTextNode(opt));
div.appendChild(a);
}
return div;
}
function makeAnchor2() {
var div = document.createElement('div');
var options = ['ENHANCEMENT 1', 'ENHANCEMENT 2'];
for(var i = 0; i < options.length; i++) {
// Create the list item:
var a = document.createElement('a');
var opt = options[i]
a.href = "./enhancements" + (i + 1) + ".html"
a.appendChild(document.createTextNode(opt));
div.appendChild(a);
}
return div;
}
window.addEventListener("load", function()
{document.getElementById('dropsc').appendChild(makeAnchor())});
window.addEventListener("load", function()
{document.getElementById('dropsc2').appendChild(makeAnchor2())});
// transfer within pages
function change() {
var service = document.getElementById("servicedrop").value;
if (service == "Select a category and service"){
document.getElementById("subject").value = "";
}
else{
sessionStorage.service = service;
document.getElementById("subject").value = sessionStorage.service;
}
sessionStorage.clear();
}
// Transfer between pages
function storeitem(item_id) {
sessionStorage.setItem("item_id", item_id);
window.location.href = "./enquiry.html";
}
function displayitem() {
var item_id = sessionStorage.getItem("item_id");
document.getElementById("subject").value = item_id;
if (item_id == "Enclosed Space Sanitisation: Home"){
document.getElementById("servicedrop").selectedIndex = "1";
};
sessionStorage.clear();
window.onload = validateForm;
}

validating using onblur and onsubmit

I would like to know how to validate a form when I use the onblur handler and the onsubmit handler at the same time. I've tried to do it and it goes straight to the submit page without displaying an error message.
Because I also have radio buttons and checkboxes, how do I validate these if the user didn't click the radio button and exclude the checkbox from validation.
Thank You
function IsNotBlank(tf, tfHelp) {
var value = tf.value;
if (value == " ") {
tf.className = "invalid ";
tfHelp.innerHTML = "This field can 't be blank.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckLetters(tf, tfHelp) {
//check empty field from previous function.
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
//assign field value
var value = tf.value;
//check if there is numbers.
var regex = new RegExp(/^[A-Za-z]{5,18}$/);
var testResult = regex.test(value);
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Use letters only and lengths must be between 5 and 18 characters.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPhNumber(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate phone number.
var regex = /^\d{8,10}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid phone number.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckEmail(tf, tfHelp) {
//check empty field
NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false) {
return false;
}
var value = tf.value;
//validate email address
var regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a valid email address.";
return false;
} else {
tf.className = "valid";
tfHelp.innerHTML = "";
return true;
}
}
function CheckPostCode(tf, tfHelp) {
//check empty field
var NotEmpty = IsNotBlank(tf, tfHelp);
if (NotEmpty == false)
return false;
var value = tf.value;
//validate postcode.
var regex = /^\d{4}$/;
var testResult = regex.test(value);
//logic
if (testResult == false) {
tf.className = "invalid";
tfHelp.innerHTML = "Please enter a 4 digit post code.";
return false;
} else {
tf.ClassName = "valid";
tfHelp.innerHTML = "";
return false;
}
}
function ValidateForm(form) {
var formCheck = true;
for (var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
//alert(form.elements[i]);
if (e.onblur) {
// alert(e.onblur());
formCheck = e.onblur() && formCheck;
}
}
return formCheck;
}
function ResetForm(form) {
//select input elements and change color back to default
var arrayInputs = document.getElementsByTagName("input");
for (var i = 0; i < arrayInputs.length; i++) {
arrayInputs[i].className = "valid";
}
//clear text on span elements
var arraySpans = document.getElementsByTagName('span ');
for (var i = 0; i < arraySpans.length; i++) {
arraySpans[i].innerHTML = "";
}
}
<form action="submit.html" onreset="ResetForm()" onsubmit="ValidateForm(this);">
<div>
<label for="fname" class="label">First Name:</label>
<input class="valid" type="text" id="txtFname" onblur="return CheckLetters(this, txtFnameHelp);" />
<span id="txtFnameHelp"></span>
</div>
<div class="one">
<label for="lname" class="label">Last Name:</label>
<input class="valid" name="lname" id="txtLname" type="text" onblur="return CheckLetters(this, txtLnameHelp);" />
<span id="txtLnameHelp"></span>
</div>
<div class="one">
<label class="label" for="phone">Phone Number:</label>
<input class="one" id="txtPhone" type="text" onblur="CheckPhNumber(this, txtPhoneHelp);"><br>
<span id="txtPhoneHelp"></span>
</div>
<div class="one">
<label for="email" class="label">Email Address:</label>
<input class="valid" id="txtEmail" type="text" onblur="CheckEmail(this, txtEmailHelp)">
<span id="txtEmailHelp"></span><br>
</div>
<div class="one">
<label class="label">Post Code:</label>
<input id="txtPostcode" type="text" onblur="CheckPostCode(this, txtPostCodeHelp);"> <br>
<span id="txtPostCodeHelp"></span>
</div>
<br>
<div>
<label>Prefered Contact Method</label><br>
</div>
<div class="one">
</--<input type="radio" name="contact" value="email">Email
</-- <input type="radio" name="contact" value="phone">Phone
</div>
<br>
<div class="one">
<label>Your Message:</label><br />
<textarea id="txtMessage" rows="8" cols="40" onblur="IsNotBlank(this, txtMessageHelp)">Your Message</textarea>
<span id="txtMessageHelp"></span>
<br><br>
</div>
</--<input class="one" type="checkbox" name="newsletter" value="subscribe">I would like to subscribe to the newsletter <br>
<div>
<input class="one" type="submit" value="Send">
<input class="one " type="Reset " value="Clear">
<br><br>
</div>
</form>
Note that these type of JavaScript code can only be debugged using Microsoft Visual Studio for some reason and would not work on using legacy text editors.
You can use below concept to perform the both action and use window.addEventListener('DOMContentLoaded'function(e) {}) to check the validation
var error_user_name = false;
function checkpw(ele, e){
var user_name = document.forms["joinform"]["user_name"].value;
if (user_name == null || user_name == "") {
text = "UserName : Required";
document.getElementById("errormsg4").innerHTML = text;
error_user_name = false;
} else {
document.getElementById("errormsg4").innerHTML = "";
error_user_name = true;
}
}
function submitall(ele, e) {
checkpw();
if(error_user_name == false) {
e.preventDefault();
} else {
console.log('form submitted');
}
}
window.addEventListener('DOMContentLoaded', function(e) { document.getElementById('user_name').addEventListener('blur', function(e) {
checkpw(this, e);
setTimeout(function() {
if (document.activeElement.id == 'join') {
document.activeElement.click();
}
}, 10);
}, false);
document.getElementById('joinform').addEventListener('submit', function(e) {
submitall(this, e);
}, false);
});
<form id="joinform" method="post" name="joinform" action="#hello">
<h2>Join</h2>
<input type="text" name="user_name" id="user_name" placeholder="User_Name"/>
<div class ="errormsg" id ="errormsg4"></div><br>
<input type="submit" name="join" id="join" value="Submit" ><br><br>
</form>

Losing variables values between form and javascript

I am having a lot of trouble with form values, first I echoed out the MYSQL insert function to see what data was attempting to be put into the database and for one MYSQL insert function it was replacing most of my entered data into '' so first I thought it was my preg_replace function in the PHP part of my code but I removed this and the same thing was still happening, I am now not sure where it has gone wrong but I am guessing somewhere between the Javascript and the form. I really am lost on where to turn now. The INSERT function for the User table works perfectly fine it picks up all the entered data but with this Member table it is a different story
Javascript
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem === "email"){
rx = /[' "]/gi;
} else if(elem === "username"){
rx = /[^a-z0-9]/gi;
} else if(elem === "mobileNumber"){
rx = /[^0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u !== ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) === true) {
_("unamestatus").innerHTML = ajax.responseText;
}
};
ajax.send("usernamecheck="+u);
}
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var m = _("mobileNumber").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var ci = _("city").value;
var pc = _("postcode").value;
var c = _("country").value;
var d = _("dateOfBirth").value;
var g = _("gender").value;
var ln = _("lastName").value;
var fn = _("firstName").value;
var status = _("status");
if(u === "" || e === "" || p1 === "" || p2 === "" || c === ""
|| g === "" || m === "" || ci === "" || pc === "" || d === "" ){
status.innerHTML = "Fill out required fields";
} else if(p1 !== p2){
status.innerHTML = "Your password fields do not match";
}else if(m.value !== 11 && isNaN(m)){
status.innerHTML = "Please enter valid mobile number";
}else if(d === "dd/mm/yyyy"){
status.innerHTML = "Please enter your date of birth";
} else {
//ajax to send form data to php
//hides sign button
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
//wait until php verifies data
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) === true) {
//if sign not succesful unhide button
if(ajax.responseText !== "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+"";
}
}
};
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ci"+ci+"&m"+m+"&pc"+pc+"&d"+d);
}
}
Form
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="email" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">
<div>Create Password:</div>
<input id="pass1" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>Confirm Password:</div>
<input id="pass2" type="password" onfocus="emptyElement('status')" maxlength="16">
<div>First name:</div>
<input id="firstName" type="text" /><br />
<div>Last name:</div>
<input id="lastName" type="text" /><br />
<div>Mobile number*:</div>
<input id="mobileNumber" onfocus="emptyElement('status')" onkeyup="restrict('mobileNumber')" maxlength="16">
<div>Gender:</div>
<select id="gender" onfocus="emptyElement('status')">
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div>Country:</div>
<select id="country" onfocus="emptyElement('status')">
<?php include_once("country_list.php"); ?>
</select>
<div>City:</div>
<input id="city" onfocus="emptyElement('status')">
<div>Postcode:</div>
<input id="postcode" onfocus="emptyElement('status')">
<div>Relationship Status*:</div>
<select id="relationshipStatus" >
<option value=""></option>
<option value="Single">Single</option>
<option value="Taken">Taken</option>
</select>
<div>Date of Birth*:</div>
<input id="dateOfBirth" type="text" onfocus="emptyElement('status')">
<button id="signupbtn" onclick="signup()">Create Account</button>
<span id="status"></span>
</form>
INSERT functions
$sql = "INSERT INTO Member (`firstName`, `lastName`, `gender`, `emailAddress`,
`city`, `country`, `postCode`, `relationshipStatus`, `mobileNumber`, `dateOfBirth`)
VALUES('$fn', '$ln', '$g', '$e', '$ci', '$c', '$pc', '$rs', '$m', '$d')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO User (`Userid`, `username`, `password`, `accountType`) VALUES ('$uid','$u','$p','$accountType')";
$query = mysqli_query($db_conx, $sql);

Categories