Transferring data between HTML pages doesn't seem to work? - javascript

I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;

There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!

I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit

Related

Why can't I have two submit buttons serving different functions?

<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts/apply.js"></script>
<script src="scripts/jobs.js"></script>
<script src="scripts/enhancements.js"></script>
<meta charset="UTF-8">
<title>SwinTech</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="applypage">
<header>
<div class="main">
<div class="logo">
<img src="logo.png" alt="logo">
</div>
<ul>
<li>
Home
</li>
<li>
Jobs
</li>
<li class="active">
Apply
</li>
<li>
About
</li>
<li>
Enhancements</li>
</ul>
</div>
</header>
<section class="applything">
<h2> Warning: you have 3 minutes to fill out the form before being redirected back to previous page </h2>
<br>
<h2>Job application:</h2>
<br>
<div class="containerr">
<form action="https://mercury.swin.edu.au/it000000/formtest.php" method="post" id="regform">
<p>Your Name: <span id="job1"></span></p>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name.." required="required" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="date of birth" value="2021-10-04" />
<br>
<br>
<label for="gender"> Select you gender</label>
<br>
<br>
<select name="gender" id="gender" required="required">
<option value="" selected>Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<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>
<br>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<label for="email">Email Address</label>
<input type="text" id="email" name="emailadd" placeholder="Your email address.." required="required">
<label for="phone">Phone Number</label>
<input type="text" id="phone" name="phonenumb" placeholder="e.g. 0451124561" minlength="8" maxlength="12" required="required">
<br>
<label>Skills</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill1" value="Javascript">
<label for="skill1"> Extensive knowledge of Javascript</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill2" value="Python">
<label for="skill2"> Extensive knowledge of Python</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill3" value="Networking">
<label for="skill3"> Extensive knowledge of Networking</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill4" value="Data Storage">
<label for="skill4"> Extensive knowledge of Data storage fundamentals</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill5" value="Security Foundations">
<label for="skill5"> Extensive knowledge of Security foundations</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill6" value="AWS Service Selection">
<label for="skill6"> Extensive knowledge of AWS service selection</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill7" value="Teamwork">
<label for="skill7"> Ability to work in a team</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill8" value="5+ Years">
<label for="skill8"> 5+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill9" value="10+ Years">
<label for="skill9"> 10+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill" name="skill10" value="20+ Years">
<label for="skill10"> 20+ years experience</label>
<br>
<br>
<input
type="checkbox"
id="other"
name="other"
value="other"
onclick="otherCheckBox()"
/>
<label for="other"> I have other skills. Please list other skills below.</label>
<br>
<br>
<br>
<label for="subject">Subject:</label>
<textarea id="otherbox" name="other skill" placeholder="textarea" style="height:200px"></textarea>
<input type="submit" value="Apply">
<br>
<br>
<input type="button" id="cancelpurchase" value="Cancel Application"></input>
</form>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div> © swintech.com | Designed by Bilal El-leissy
</div>
</body>
</html>
"use strict"
function otherCheckBox() {
var checkBox = document.getElementById("other"); //Getting the 'other' CheckBox
var otherBox = document.getElementById("otherbox"); //Getting the TextBox
if (checkBox.checked) {
otherBox.required = "true"; //Setting the 'required' parameter to true if checkbox is checked
} else {
otherBox.required = ""; //Setting the 'required' parameter to false if the checkbox is not checked
}
}
function validate() {
var errMsg = "";
var result = true;
var gender = document.getElementById("gender").value;
var start = document.getElementById("start").value;
var skill = document.getElementById("skill").value;
var other = document.getElementById("other").value;
var otherbox = document.getElementById("otherbox").value;
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[
document.getElementById("state").selectedIndex
].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
if (!postcode.match(regex)) {
errMsg = errMsg + "State and postcode do not match\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
storeBooking(
fname,
lname,
start,
email,
gender,
phone,
streetname,
suburb,
state,
postcode,
other,
otherbox
);
}
return result;
}
function storeBooking(
fname,
lname,
start,
email,
gender,
phone,
streetname,
suburb,
state,
postcode,
skill,
other,
otherbox
) {
sessionStorage.fname = fname;
sessionStorage.lname = lname;
sessionStorage.start = start;
sessionStorage.email = email;
sessionStorage.gender = gender;
sessionStorage.phone = phone;
sessionStorage.streetname = streetname;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.skill = skill;
sessionStorage.other = other;
sessionStorage.otherbox = otherbox;
}
function getBooking() {
if (sessionStorage.fname != undefined) {
document.getElementById("confirm_fname").textContent = sessionStorage.fname;
document.getElementById("confirm_lname").textContent = sessionStorage.lname;
document.getElementById("confirm_email").textContent = sessionStorage.email;
document.getElementById("confirm_gender").textContent = sessionStorage.gender;
document.getElementById("confirm_phone").textContent = sessionStorage.phone;
document.getElementById("confirm_start").textContent = sessionStorage.start;
document.getElementById("confirm_streetname").textContent = sessionStorage.streetname;
document.getElementById("confirm_suburb").textContent = sessionStorage.suburb;
document.getElementById("confirm_state").textContent = sessionStorage.state;
document.getElementById("confirm_postcode").textContent = sessionStorage.postcode;
document.getElementById("confirm_skill").textContent = sessionStorage.skill;
document.getElementById("confirm_other").textContent = sessionStorage.other;
document.getElementById("confirm_otherbox").textContent = sessionStorage.otherbox;
document.getElementById("a_fname").value = sessionStorage.fname;
document.getElementById("a_lname").value = sessionStorage.lname;
document.getElementById("a_email").value = sessionStorage.email;
document.getElementById("a_gender").value = sessionStorage.gender;
document.getElementById("a_phone").value = sessionStorage.phone;
document.getElementById("a_start").value = sessionStorage.start;
document.getElementById("a_streetname").value = sessionStorage.streetname;
document.getElementById("a_suburb").value = sessionStorage.suburb;
document.getElementById("a_state").value = sessionStorage.state;
document.getElementById("a_postcode").value = sessionStorage.postcode;
document.getElementById("a_skill").value = sessionStorage.skill;
document.getElementById("a_other").value = sessionStorage.other;
document.getElementById("a_otherbox").value = sessionStorage.otherbox;
}
}
function prefillcard()
{
document.getElementById("fname").value = sessionStorage.fname;
document.getElementById("lname").value = sessionStorage.lname;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("gender").value = sessionStorage.gender;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("start").value = sessionStorage.start;
document.getElementById("streetname").value = sessionStorage.streetname;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("skill").value = sessionStorage.skill;
document.getElementById("other").value = sessionStorage.other;
document.getElementById("otherbox").value = sessionStorage.otherbox;
}
window.addEventListener("DOMContentLoaded", prefillcard);
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = function() {
init();
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
//Add a zero if one Digit (eg: 05,09)
if (dd < 10) {
dd = "0" + dd;
}
//Add a zero if one Digit (eg: 05,09)
if (mm < 10) {
mm = "0" + mm;
}
var minYear = yyyy - 80; //Calculate Minimun Age (<80)
var maxYear = yyyy - 15; //Calculate Maximum Age (>18)
var min = minYear + "-" + mm + "-" + dd;
var max = maxYear + "-" + mm + "-" + dd;
document.getElementById("start").setAttribute("min", min);
document.getElementById("start").setAttribute("max", max);
};
(function () { //Enhancement 1
setTimeout(function () {
history.back();
}, 180000);
})();
function cancelBooking(){ //Enhancement 2
window.location = "index.html";
sessionStorage.clear();
}
function init() {
document.getElementById("cancelpurchase").addEventListener("click", cancelBooking);
getBooking();
}
I've set up a form with a submit and cancel button, with the submit button sending all the inputted data to the server and the cancel button sending the user to the homepage. For some reason, only one or the other can be there at the same time and cannot coexist. If my cancel button is activated, I can still submit to the server and cancel the form but all my validation doesn't work. The two separate snippets are in two separate external JavaScript files linked to the same HTML.
Note: no jQuery or Inline JavaScript.
The issue is that both of the buttons have type "submit".
<input type="submit" value="Apply">
<br>
<br>
<input type="submit" id="cancelpurchase" value="Cancel Application"></input>
It causes form to be submitted (and trigger the onsubmit event correspondingly) - and that is default behaviour for any browser.
To resolve the issue - set type="button" for your cancel button.

Why does my JavaScript file crash without any apparent errors?

function validate() {
var errMsg = "";
var result = true;
var fname = document.getElementById("fname").value;
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name correctly.\n";
result = false;
}
var lname = document.getElementById("lname").value;
if (!lname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your last name correctly.\n";
result = false;
}
var email = document.getElementById("email").value;
if (!email.match(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$/)) {
errMsg += "Please enter your email correctly.\n";
result = false;
}
var streetname = document.getElementById("streetname").value;
if (!streetname.match(/^[a-zA-Z0-9\s]+$/)) {
errMsg += "Please enter your street name correctly.\n";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (!suburb.match(/^[a-zA-Z\-]+$/)) {
errMsg += "Please enter your suburb correctly.\n";
result = false;
}
var phone = document.getElementById("phone").value;
if (!phone.match(/[0-9]{9}/)) {
errMsg += "Please enter your phone number correctly.\n";
result = false;
}
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[
document.getElementById("state").selectedIndex
].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
if (!postcode.match(regex)) {
errMsg = errMsg + "State and postcode do not match\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
storeBooking(
fname,
lname,
email,
phone,
streetname,
suburb,
state,
postcode
);
}
return result;
}
function storeBooking(
fname,
lname,
email,
phone,
streetname,
suburb,
state,
postcode
) {
sessionStorage.fname = fname;
sessionStorage.lname = lname;
sessionStorage.email = email;
sessionStorage.phone = phone;
sessionStorage.streetname = streetname;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
window.onload = function() {
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yyyy = date.getFullYear();
//Add a zero if one Digit (eg: 05,09)
if (dd < 10) {
dd = "0" + dd;
}
//Add a zero if one Digit (eg: 05,09)
if (mm < 10) {
mm = "0" + mm;
}
minYear = yyyy - 80; //Calculate Minimun Age (<80)
maxYear = yyyy - 15; //Calculate Maximum Age (>18)
var min = minYear + "-" + mm + "-" + dd;
var max = maxYear + "-" + mm + "-" + dd;
document.getElementById("start").setAttribute("min", min);
document.getElementById("start").setAttribute("max", max);
};
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts/part2.js"></script>
<meta charset="UTF-8">
<title>SwinTech</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="applypage">
<header>
<div class="main">
<div class="logo">
<img src="logo.png" alt="logo">
</div>
<ul>
<li>
Home
</li>
<li>
Jobs
</li>
<li class="active">
Apply
</li>
<li>
About
</li>
</ul>
</div>
</header>
<section class="applything"><h2>Job application:</h2>
<br>
<div class="containerr">
<form action="https://mercury.swin.edu.au/it000000/formtest.php" method="post" id="regform">
<label>Job Reference Number</label>
<input type="text" id="onlyletters" name="onlyletters" pattern="[a-zA-Z0-9]+" minlength="5" maxlength="5" placeholder="Reference number for specified job.." required="required">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name.." required="required" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="trip-start" value="2021-10-02" />
<br>
<br>
<label for="gender"> Select you gender</label>
<br>
<br>
<select name="gender" id="gender" required="required">
<option value="" selected>Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<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>
<br>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<label for="email">Email Address</label>
<input type="text" id="email" name="emailadd" placeholder="Your email address.." required="required">
<label for="phone">Phone Number</label>
<input type="text" id="phone" name="phonenumb" placeholder="e.g. 0451124561" minlength="8" maxlength="12" required="required">
<br>
<label>Skills</label>
<br>
<br>
<input type="checkbox" id="skill1" name="skill1" value="Javascript">
<label for="skill1"> Extensive knowledge of Javascript</label>
<br>
<br>
<input type="checkbox" id="skill2" name="skill2" value="Python">
<label for="skill2"> Extensive knowledge of Python</label>
<br>
<br>
<input type="checkbox" id="skill3" name="skill3" value="C#">
<label for="skill3"> Extensive knowledge of Networking</label>
<br>
<br>
<input type="checkbox" id="skill4" name="skill4" value="C#">
<label for="skill4"> Extensive knowledge of Data storage fundamentals</label>
<br>
<br>
<input type="checkbox" id="skill5" name="skill5" value="C#">
<label for="skill5"> Extensive knowledge of Security foundations</label>
<br>
<br>
<input type="checkbox" id="skill6" name="skill6" value="C#">
<label for="skill6"> Extensive knowledge of AWS service selection</label>
<br>
<br>
<input type="checkbox" id="skill7" name="skill7" value="C#">
<label for="skill7"> Ability to work in a team</label>
<br>
<br>
<input type="checkbox" id="skill8" name="skill8" value="C#">
<label for="skill8"> 5+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill9" name="skill9" value="C#">
<label for="skill9"> 10+ years experience</label>
<br>
<br>
<input type="checkbox" id="skill10" name="skill10" value="C#">
<label for="skill10"> 20+ years experience</label>
<br>
<br>
<input
type="checkbox"
id="other"
name="other"
value="other"
onclick="otherCheckBox()"
/>
<label for="other"> I have other skills. Please list other skills below.</label>
<br>
<br>
<br>
<label for="subject">Subject:</label>
<textarea id="otherbox" name="subject" placeholder="textarea" style="height:200px"></textarea>
<input type="submit" value="Apply">
</form>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div> © swintech.com | Designed by Bilal El-leissy
</div>
</body>
</html>
My JavaScript crashes even though there are no apparent errors when I check the console on Chrome. I've tried rearranging and removing certain functions from the JavaScript but there doesn't seem to be a particular pattern so I cannot determine which piece of code is crashing the rest of it.
What specifically happens is that all my validation stops working except my date of birth validation.
Note: Cannot use inline JavaScript or jQuery.
Thank You for clarifying.
The problem is with init() method.
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
window.onload = function() {
var date = new Date();
var dd = date.getDate();
In this piece of code window.onload = init; You assign init function to window.onload and after that immediately reassign window.onload with function() {..}
So Your init() function is never called.
Try to move init function call like this:
window.onload = function() {
init();
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
... }

Implementing Submit action in javascript

I am new to javascript..I am facing some problems while trying to implement form submit action onclick using javascript..
The problem is when I implement all the validation checks using if-else conditions ..The function dose not produce any result..
[] 1[]2
I have implemented various validation check and tried to capture all possible form elements with different conditions..But I am failing when I am implementing validation check..otherwise the code works -I cannot figure out what is the problem..
Here is the code:
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNAN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNAN(ag) || ag.parseInt() > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
</head>
<body style="background:pink;">
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>
The first error is at these lines
var nam=document.getElementById("student_name").value;
if(nam.value.length==0 || !(isNAN(nam)) || nam.value.length>20){
nam="Invalid";
}
nam is the value of the input again doing nam.value will throw an error
Secondly isNAN is not a javascript inbuilt function. Case matters while using in build function , it has to be isNaN
Thirdly ag.parseInt() is wrong. Instead it has to be parseInt(ag,10) where 10 is the radix
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNaN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNaN(ag) || parseInt(ag, 10) > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
This might help you
function submitForm()
{
var nam = document.getElementById("student_name").value;
if (!(nam) || nam.length > 20)
{
alert("please Select a valid name");
return false;
}
var ag = document.getElementById("student_age").value;
if (!(ag) || ag > 100)
{
alert("please Select a valid age");
return false;
}
var gender = "";
if(!document.getElementById("g1").checked && !document.getElementById("g2").checked )
{
alert("please Select gender");
return false;
}
else
{
if(document.getElementById("g1").checked)
{
gender = document.getElementById("g1").value;
}
else
{
gender = document.getElementById("g2").value;
}
}
var cty = document.getElementById("city").value;
if (!(cty) || cty=="Default")
{
alert("please Select a city");
return false;
}
var hobbies ="";
if(!document.getElementById("h1").checked && !document.getElementById("h2").checked && !document.getElementById("h3").checked)
{
alert("please Select hobby");
return false;
}
else
{
var inputElements = document.getElementsByName("cbox");
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
var value=" "+ inputElements[i].value;
hobbies +=value;
}
}
}
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body style="background:pink;">
<div id="body">
<form action="#" method="post" onsubmit="return false">
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Default">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label>
<input type="checkbox" id="h1" name="cbox" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
<input type="submit" value="Submit" onclick="submitForm()">
</form>
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>

How to stop user for using same username which already exist in my local storage?

var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function agecal() {
var Bdate = inputsarray[4].value;
var Bday = +new Date(Bdate).getFullYear();
var age = (new Date().getFullYear() - Bday);
inputsarray[5].value = age;
}
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
} else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) users.Purpose += " Storing Apps";
if (inputsarray[9].checked === true) users.Purpose += " Storing Sites";
if (inputsarray[10].checked === true) users.Purpose += " Fun";
array.push(users);
localStorage.setItem("Users Data: ", JSON.stringify(array));
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
for (var i = 0; i < arrayobjfromls.length; i++) {
if (inputsarray[2].value === arrayobjfromls[i].UserName) {
alert("This username is already in use. Please try another.");
localStorage.removeItem(arrayobjfromls[i]);
}
}
}
<div>
<center>
<form action="javascript:void(0);" method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="password" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" onchange="agecal();" />
<br/>
<label>Age:</label>     
<input type="text" id="age" disabled="disabled" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Please help me I want to stop user for using username which already present in my local storage by showing an alert and also I don't want to send data to local storage in which username is same of that data which is already present in my local storage...so that my local storage contain only those objects which have different usernames.
You're already checking for this; you're just doing it after you've already added the new user. Do the check first:
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
var found = false;
for (var i = 0; i < arrayobjfromls.length; i++) {
if(users.UserName === arrayobjfromls[i].UserName) {
found = true;
break;
}
}
if ( found ) {
alert("This username is already in use. Please try another.");
} else {
array.push( users );
localStorage.setItem("Users Data: ", JSON.stringify(array));
}

Simple JavaScript validation not working?

Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>

Categories

Resources