I'm getting an NaN error whenever I run this? - javascript

I heard that NaN errors are when you are trying to pass an object as a number, yet in my HTML, 'productquantity' is set as a number, so why is it giving me this error? These files operate with another HTML file and another JavaScript file to retrieve data and these 2 display the data. 'productquantity is what is my only hurdle and where the NaN error comes up. If you need the other HTML and Javascript file, please let me know. Thanks in advance!
"use strict";
function getBooking() {
var laptopsprice = 0;
if (sessionStorage.fname != undefined) { //if sessionStorage for username is not empty
//confirmation text
//outputs user details in payment page and stores values to be sent to server in hidden input tags
document.getElementById("confirm_name").textContent = sessionStorage.fname + " " + sessionStorage.lname;
document.getElementById("confirm_email").textContent = sessionStorage.email;
document.getElementById("confirm_phone").textContent = sessionStorage.phone;
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_laptops").textContent = sessionStorage.laptops;
document.getElementById("confirm_productquantity").textContent = Number(sessionStorage.productquantity);
document.getElementById("confirm_cost").textContent = laptopsprice;
laptopsprice = totalproductcost(sessionStorage.laptops, Number(sessionStorage.productquantity));
//values for hidden input tags that send data to the server
document.getElementById("a_name").value = sessionStorage.fname + " " + sessionStorage.lname;
document.getElementById("a_email").value = sessionStorage.email;
document.getElementById("a_phone").value = sessionStorage.phone;
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_laptops").textContent = sessionStorage.laptops;
document.getElementById("a_productquantity").textContent = Number(sessionStorage.productquantity);
document.getElementById("a_cost").value = laptopsprice;
}
}
function totalproductcost(laptops , productquantity) {
var laptopsprice;
if (laptops == "Workstation_Laptop") {
laptopsprice = (productquantity * 2499);
} else if (laptops == "Gaming_Laptop") {
laptopsprice = (productquantity * 1789);
} else if (laptops == "Laptop_Stand") {
laptopsprice = (productquantity * 64);
} else if (laptops == "Office_Laptop") {
laptopsprice = (productquantity * 1499);
}
return laptopsprice;
}
function cancelBooking(){
window.location = "enquiries.html";
sessionStorage.clear();
}
//function for invoking getbooking and validate, cancel booking
function init() {
document.getElementById("paymentform").onsubmit = validate;
document.getElementById("cancelpurchase").addEventListener("click", cancelBooking);
getBooking();//invokes getbooking function
}
//invokes init fuction on window load
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts/payment.js"></script>
<title>SwinTech</title>
<link rel="stylesheet" type="text/css" href="css/style.css"> </head>
<header class="enquiriespage">
<div class="main">
<div class="logo"> <img src="logo.png" alt="logo"> </div>
<ul>
<li>Home</li>
<li>Products</li>
<li>Enquiries</li>
<li class="active">>Payment</li>
<li>About</li>
</ul>
</div>
</header>
<section class="paymentthing">
<div class="paymentcontainer">
<fieldset>
<legend>Order Summary:</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Your Email: <span id="confirm_email"></span></p>
<p>Your Phone Number: <span id="confirm_phone"></span></p>
<p>Street name: <span id="confirm_streetname"></span></p>
<p>Suburb: <span id="confirm_suburb"></span></p>
<p>State: <span id="confirm_state"></span></p>
<p>Postcode: <span id="confirm_postcode"></span></p>
<p>Product: <span id="confirm_laptops"></span></p>
<p>Product Quantity: <span id="confirm_productquantity"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="name" id="a_name" />
<input type="hidden" name="email" id="a_email" />
<input type="hidden" name="phone" id="a_phone" />
<input type="hidden" name="streetname" id="a_streetname" />
<input type="hidden" name="suburb" id="a_suburb" />
<input type="hidden" name="state" id="a_state" />
<input type="hidden" name="cost" id="a_cost" />
<input type="hidden" name="laptops" id="a_laptops" />
<input type="hidden" name="postcode" id="a_postcode" />
<input type="hidden" name="productquantity" id="a_productquantity" />
</fieldset>
<br>
<br>
<form id="paymentform" method="post" action="https://mercury.swin.edu.au/it000000/formtest.php">
<label for="cardType">Please Choose a Card Type:</label>
<br>
<br>
<select name="cardType" id="cardType" required="required">
<option value="">Please Select</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
<option value="American Express">AmEx</option>
</select>
<br>
<br>
<label for="cardName" id="cardName">Please Enter Name On Card:</label>
<input type="text" name="cardName" maxlength="40" required="required">
<br>
<br>
<label>Please Enter Credit Card Expiration Date:</label> <span class="expiration">
<input type="tel" name="month" placeholder="MM" maxlength="2" size="2" required="required" />
<span>/</span>
<input type="tel" name="year" placeholder="YY" maxlength="2" size="2" required="required" /> </span>
<br>
<br>
<br>
<label for="cardNo">Credit Card Number:</label>
<input id="cardNo" type="tel" inputmode="numeric" pattern="[0-9\s]{13,19}" autocomplete="cc-number" maxlength="16" placeholder="xxxx xxxx xxxx xxxx" required="required">
<br>
<br>
<input type="submit" value="Check Out">
<br>
<br>
<button type="button" id="cancelpurchase">Cancel Purchase</button>
</form>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div> © swintech.com | Designed by Bilal El-leissy </div>
</html>

Anytime you retrieve or set a value to go in a html tag or form element it is a string. Even if you cast that item as a Number(), the DOM will store it as a string. Whenever that string is to be used in a calculation, convert it to a number then with the plus operator, parseInt or parseFloat, as in:
function totalproductcost(laptops , productquantity) {
productquantity = +productquantity;
// OR productquantity = parseInt(productquantity);
// OR productquantity = parseFloat(productquantity); if you have a decimal to consider
var laptopsprice;
if (laptops == "Workstation_Laptop") {
laptopsprice = (productquantity * 2499);
} else if (laptops == "Gaming_Laptop") {
laptopsprice = (productquantity * 1789);
} else if (laptops == "Laptop_Stand") {
laptopsprice = (productquantity * 64);
} else if (laptops == "Office_Laptop") {
laptopsprice = (productquantity * 1499);
}
return laptopsprice;
}

There are two things you might want to check for.
One is that productquantity has a value. If it's undefined or null, Number will return NaN.
The other is that if productquantity is being set as a string, that the string doesn't contain non-numerical characters.

Adding ".value" to the input helped me

Related

check the Value for standard manufacturing thickness and display a massage if pass or not

I need to to enter a new value( the standard manufacturing thickness(SMT)) and divid it on /48 then check if the answer < 135 display (pass) if not display (Enter higher value) I tried if else statement but it doesn't work
and also I want to display the (the standard manufacturing thickness(SMT=)) text input side by side with the MAOP(psi)= text input.
<body>
<label for="formulas">Choose a formula:</label>
<select name="formulas" id="formulas">
<option value="free">Pipeline Thickness</option>
</select>
<h2>Enter inputs</h2>
<label for="P">MAOP(psi)=</label>
<input type="number" id="P">
<br>
<label for="D=">Do(in)=</label>
<input type="number" id="D">
<br>
<label for="SMYS">SMYS(psi)=</label>
<input type="number" id="SMYS">
<br>
<label for="DF">DF=</label>
<input type="number" id="DF">
<br>
<label for="T">T=</label>
<input type="number" id="T">
<br>
<label for="E">E ⅉ=</label>
<input type="number" id="E">
<br>
<button type="submit" id="calculate">calculate</button>
<br>
<label for="total">Wall Thickness(in)=</label>
<input type="number" id="total" readonly>
<br>
<label for="SMT">Standerd Manufacturing Thickness (in)=</label>
<input type="number" id="SMT">
<br>
<button type="submit" id="check">Check</button>
<script>
document.getElementById('calculate').addEventListener('click', function() {
var P = +document.getElementById("P").value;
var D = +document.getElementById("D").value;
var SMYS = +document.getElementById("SMYS").value;
var DF = +document.getElementById("DF").value;
var T = +document.getElementById("T").value;
var E = +document.getElementById("E").value;
var SMT = +document.getElementById("SMT").value;
var total = (P * D) / (2 * SMYS * DF * T * E);
document.getElementById("total").value = total;
var Check= (SMT / 48);
function myFunction() {
document.getElementById("Check").value = Check;
}
if (SMT / 48 < 135) {
console.log("pass");
} else {
console.log("enter higher value");
}
});
</script>
</body>

Why isn't this function storing variables and why isn't it validating the first name?

Why isn't this function storing variables and why isn't it validating the first name? It won't work for some reason. There are no error messages in the console when I open the website. Please help, this is very annoying and I've been struggling with this for a while. Is there something going past the error messages that are stopping my JavaScript code from working?
"use strict";
function validate() {
var errMsg = "";
var result = true;
// get variables from form and check rules
// if something is wrone set result to false and add error message
var fname = document.getElementById("fname").value; //validates first name
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name (Only alpha characters).\n";
result = false;
}
/*get variables from form and check rules*/
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,
productquantity
);
}
return result;
}
function storeBooking(
fname,
lname,
email,
phone,
streetname,
suburb,
state,
postcode,
productquantity
) {
sessionStorage.fname = fname;
sessionStorage.lname = lname;
sessionStorage.email = email;
sessionStorage.phone = phone;
sessionStorage.streetname = streetname;
sessionStorage.suburb = suburb;
sessionStorage.state = state;
sessionStorage.postcode = postcode;
sessionStorage.productquantity = productquantity;
}
// this stores values inside of sessionStorage
function init() {
var regForm = document.getElementById("regform"); // get ref to the HTML element
regForm.onsubmit = validate; //register the event listener
}
window.onload = init;
<!DOCTYPE html>
<html lang="en">
<head>
<script src="scripts/part2.js"></script>
<title>SwinTech</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="enquiriespage">
<header>
<div class="main">
<div class="logo">
<img src="logo.png" alt="logo">
</div>
<ul>
<li>Home</li>
<li>Products</li>
<li class="active">Enquiries</li>
<li>About</li>
</ul>
</div>
</header>
</body>
<section class="enquirything">
<div class="containerr">
<form action="payment.html" id="regform" method="post">
<label for="fname">First Name</label>
<input type="text" id="fname" name="fname" required="required" placeholder="Your name.." 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="fname" required="required" placeholder="Your last name.." onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="email">Email Address</label>
<br>
<br>
<input type="email" id="email" name="emailadd" required="required" placeholder="Your email address..">
<br>
<br>
<label for="phone">Phone Number</label>
<br>
<br>
<input type="text" id="phone" name="txtChar" required="required" placeholder="e.g. 0451124561" maxlength="10">
<br>
<br>
<h1>Address</h1>
<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>
<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}$">
<fieldset>
<br>
<h1>Product Selection</h1>
<br>
<label for="productselection">Please select the product:</label>
<br>
<select id="productselection" name="Product" >
<option value="none">Please Select a Product</option>
<option value="Workstation-Laptop">Workstation Laptop</option>
<option value="Gaming-Laptop">Gaming Laptop</option>
<option value="Laptop-Stand">Laptop Stand</option>
<option value="Office-Laptop">Office Laptop</option>
</select>
<br>
<h1>Amount of Product:</h1>
<section>
<br>
<input type="number" id="productquantity" />
<br>
</section>
</fieldset>
<br>
<input type="submit" value="Pay Now"> <input type="reset" value="Reset" />
</fieldset>
</form>
</div>
</section>
<div class="footer">
<div class="footer-content"></div>
<div class="footer-bottom"></div>
© swintech.com | Designed by Bilal El-leissy
</div>
</html>
The code looks fine, but judging by this code, I'm taking a stab in the dark and saying you're hitting a security error, likely due to not serving the file, and using file:// in the browser instead of http[s]:// . You can see the proper error if you halt the code from completing the submit.
function validate(event) {
event.preventDefault();
From MDN:
The request violates a policy decision, or the origin is not a valid scheme/host/port tuple (this can happen if the origin uses the file: or data: scheme, for example). For example, the user may have their browser configured to deny permission to persist data for the specified origin.

How save text format date save in session

I'm saving the form data in javascript sessions every value I'm getting the correct values after submitting the form. but when I click back to my form there is date format not saving the correct format of date which I filled on submitting time.
15/11/1992 date format ( working fine when I'm submitting the form/)
15,11,1992( getting this value in session when I reload the page)
"use strict";
//********************* get and set details ******************
function getDetails(){
if (typeof(Storage)!=="undefined"){
if (sessionStorage.getItem("fName") !== null){
document.getElementById("fName").value = sessionStorage.getItem("fName");
}
if (sessionStorage.getItem("lName") !== null){
document.getElementById("lName").value = sessionStorage.getItem("lName");
}
if (sessionStorage.getItem("dob") !== null){
document.getElementById("dob").value = sessionStorage.getItem("dob");
}
if (sessionStorage.getItem("gender") !== null){
document.getElementById("gender").value = sessionStorage.getItem("gender");
}
if (sessionStorage.getItem("street_address") !== null){
document.getElementById("street_address").value = sessionStorage.getItem("street_address");
}
if (sessionStorage.getItem("town") !== null){
document.getElementById("town").value = sessionStorage.getItem("town");
}
if (sessionStorage.getItem("state") !== null){
document.getElementById("state").value = sessionStorage.getItem("state");
}
if (sessionStorage.getItem("postcode") !== null){
document.getElementById("postcode").value = sessionStorage.getItem("postcode");
}
if (sessionStorage.getItem("phone") !== null){
document.getElementById("phone").value = sessionStorage.getItem("phone");
}
if (sessionStorage.getItem("other") !== null){
document.getElementById("other").value = sessionStorage.getItem("other");
}
if (sessionStorage.getItem("otherText") !== null){
document.getElementById("otherText").value = sessionStorage.getItem("otherText");
}
}
}
function setDetails(fName, lName, dob,gender,street_address,town,state,postcode,phone,other,otherText) {
if (typeof(Storage)!=="undefined"){
sessionStorage.setItem("fName", fName);
sessionStorage.setItem("lName", lName);
sessionStorage.setItem("dob", dob);
sessionStorage.setItem("gender", gender);
sessionStorage.setItem("street_address", street_address);
sessionStorage.setItem("town", town);
sessionStorage.setItem("postcode", postcode);
sessionStorage.setItem("phone", phone);
sessionStorage.setItem("other", other);
sessionStorage.setItem("otherText", otherText);
}
}
//********************* get and set Job Ref ******************
function setJobRef (jobRefNumber){
if(typeof(Storage)!=="undefined"){
localStorage.setItem("jobRef", jobRefNumber);
}
}
function getJobRef (){
if(typeof(Storage)!=="undefined"){
if (localStorage.getItem("jobRef") !== null) {
var jobRef= document.getElementById("jobRef");
jobRef.value = localStorage.getItem("jobRef");
}
}
}
//********************* validate ******************
function validate() {
var errMsg="";
var result=true;
var fName=document.getElementById("fName").value;
var lName=document.getElementById("lName").value;
var dob = document.getElementById("dob").value.split("/");
var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
var today = new Date();
var age = today.getFullYear() - date.getFullYear();
var gender = document.getElementById("gender").value;
var street_address = document.getElementById("street_address").value;
var town = document.getElementById("town").value;
var postcode = document.getElementById("postcode").value;
var phone=document.getElementById("phone").value;
var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
var other = document.getElementById("other").checked;
var otherText = document.getElementById("otherText").value;
if (fName=="") {
errMsg += "Please enter your first name.<br>";
result=false;
}
if (lName=="") {
errMsg += "Please enter your last name.<br>";
result=false;
}
if (dob=="")
{
errMsg += "Please enter your date of birth.<br>";
result=false;
}
if (age >= 80)
{ // Outside age ranges.
errMsg +="You must be 80 or younger to apply for this job\n";
result = false;
}
if (age <= 15)
{ // Outside age ranges.
errMsg += "You must be 15 or older to apply for this job\n";
result = false;
}
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 += "State and postcode do not match\n";
result = false;
}
if (other && document.getElementById("otherText").value.trim().length===0)
{
errMsg += "You have selected other skills, you must enter one other skill in the text box\n";
result = false;
}
// more validation here
if (errMsg!="")
document.getElementById("err").innerHTML=errMsg;
else { // no error, save data to storage
setDetails(fName,lName,dob,gender,street_address,town,state,postcode,phone,other,otherText);
}
return result;
}
//********************* init ******************
function init() {
if (document.getElementById("applyPage")!=null) { // apply page init
getJobRef();
getDetails();
document.getElementById("applyForm").onsubmit = validate;
}
else if (document.getElementById("positionPage")!=null) { // position page init
var applylinks=document.getElementsByClassName("applylink"); // array
for (var i=0; i<applylinks.length; i++)
applylinks[i].onclick = function () { setJobRef(this.id); }
}
}
window.onload = init;
***HTML****
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Student personal detail" />
<meta name="keywords" content="Peronal Details of volunteer or student," />
<meta name="author" content="Name student " />
<link rel="stylesheet" type="text/css" href="styles/style.css" media="screen" />
<script src="my.js"></script>
<title>Apply to Voulnteer</title>
</head>
<body id="applyPage">
<div id="leftsidebar">
<!-- menu -->
<header id="header">
<h1>Imagine a world free from Cancer. Help make it a reality.</h1>
<div id="menu">
<ul>
<li>Home</li>
<li>Positions</li>
<li>Apply Now</li>
<li>Details</li>
<li>Enhancements</li>
</ul>
</div>
</header>
<!-- menu end -->
<!-- right hand side content -->
<aside class="rightnews">
<span class="style3">Current Happenings</span><br />
<img src="images/bullet.gif" alt="blue" width="19" height="16" /><br /> <br />
<img src="images/cancer_awareness_month.jpeg" alt="cancer_awareness_month" width="130" height="95" /><br /><br />
<img src="images/breast_cancer.png" alt="breast cancer" width="130" height="93" /><br /><br />
<img src="images/month.jpeg" alt="awareness_month" width="130" height="99" />
<br />
</aside>
<!-- right hand side content end -->
<!-- left hand side content -->
<aside id="f">
<h2 >About Volunteering:</h2>
<div class="leftnews">
<img src="images/Vol3.png" alt="blue" style="width: 140px;height: 100px;"><br />
As an Melbourne Red Cross volunteer you can honor a survivor or a loved one lost to cancer, help save lives of people in your local community, and around the world. It only takes a little time to do a lot of good. Discover how rewarding it is to be a volunteer.
<br />
<br />
</div>
</aside>
<!-- left hand side content end -->
<!-- center side content -->
<div id="content"><br/><br/>
<h2 class="style7">Apply Now</h2>
<div class="style3">
<form id="applyForm" method="post" action="https://mercury.swin.edu.au/it000000/formtest.php">
<p id="err"></p>
<p><label for = "jobRef">Job Reference Number: </label>
<input name= "jobRef" id="jobRef" readonly/></p>
<p><label for = "fName">First Name: </label>
<input name= "fName" id="fName" /></p>
<p><label for = "lName">Last Name: </label>
<input name= "lName" id="lName" /></p>
<p><label for="dob">*Date of Birth:</label>
<input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" maxlength="10" size="10"/></p>
<p id="err"></p>
<fieldset>
<legend>Gender:</legend>
<input type = "radio" name = "gender" id="gender" value = "male"> Male
<input type = "radio" name = "gender" id="gender" value = "female"> Female
</fieldset>
<br>
<label for="street"> Street Address:</label><br>
<input type="text" name="street_address" id="street_address" required pattern="[A-Za-z]{1,40}">
<br>
<label for="town"> Suburb/Town </label><br>
<input type="text" name="town" id="town" required pattern="[A-Za-z]{1,40}">
<p><label for="state">*State:</label>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="WIC">WIC</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 id="err"></p>
</p>
<p><label for="postcode">*Postcode:</label>
<input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" />
</p>
<label for="phone"> Phone Number </label><br>
<input type="tel" name="phone" maxlength="12" pattern="[0-9]{8,12}" id="phone" />
<br>
<p>Skill list:</p>
<p><label for="Dancing">Dancing</label>
<input type="checkbox" id="Dancing" name="skills[]" checked="checked" value="Dancing" /></p>
<p><label for="Singing">Singing</label>
<input type="checkbox" id="Singing" name="skills[]" value="Singing" /></p>
<p><label for="other">Other Skills:</label>
<input type="checkbox" id="other" name="skills" /></p>
<textarea id="otherText" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
<p><input type= "submit" value="Apply"/>
<input type= "reset" value="Reset"/></p>
</form>
</div>
<br>
</div>
<!-- right hand side content -->
<!-- Footer -->
<div id="footer">Copyright © 2019 Melbourne Red Cross Society</div>
<!--footer end -->
</div>
</body>
</html>
If you are referring to the "dob" field, I would personally not try to store that as a date object. In my experience, this can cause issues when your user is in a different time zone as your server. People are not entering a timestamp of when they were born, they are entering the calendar day. So even if I was born on January 1st in my time zone, and it was December 31st in your time zone at that time, you would not say my birthday is December 31st. Really what you care about is the day, month, and year.
Another note, it would be much cleaner to store your session storage properties in a list, then iterate over the list like so:
function getDetails(){
if (typeof(Storage)==="undefined"){
return; // return early to avoid code clutter
}
let properties = ['fName', 'lName', 'dob', 'blah', 'blah', 'blah'];
properties.forEach(p => {
if (sessionStorage.getItem(p) !== null){
document.getElementById(p).value = sessionStorage.getItem(p);
}
});
}

cant seem to get Javascript connecting or working

I am currently doing a unit task and am having trouble working out why my javascript wont connect. i have tried a few things but cant seem to work it out. Im sure its easy but i just cant work it out. an explanation would be great too.
There are two files one html and one javascript.
Thanks in advance
HTML
<script src="validate.js"></script>
</head>
<body>
<header>
<h1>Rohirrim Ranch Tours</h1>
<h2>Booking Form</h2>
</header>
<form id="regform" method="post"
action="https://mercury.swin.edu.au/it000000/formtest.php"
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>
<p><label for="beard">Enter your beard length in inches</label><br />
0 <input type="range" id="beard" name="beard" min="0"
max="60"> 60
</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>
</form>
JAVASCRIPT
"use strict";
function validate() {
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var errMsg = "";
var result = true;
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;
}
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;
}
if (erMsg !== ""){
alert(errMsg);
}
return result;
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
I see your error erMsg instead of errMsg
if (erMsg !== ""){
alert(errMsg);
}
and also add event.preventDefault(); at the beginning of the validate function
Your js reference is fine :)
Try setting the Javascript url as './validate.js'

javascript: submit button pulls all values from the textboxes and displays them in a p tag

So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>

Categories