I have been working on this project for school for several weeks now and have came here several times to point me back in the right direction, so thank you for that.
This is the issue I (and my instructor) are struggling over.
I have to create an order form (...yep) where the user must select a computer case, monitor, and printer. The picture must appear next to the selection and the price must update. If everything checks the order submits, if not you get an alert asking to complete the form. You also have the option to reset or clear the form. Everything work wonderfully except the clear function. All fields reset including the price, however the individual values are still being held. If I pick the first option on all sections the total is $1000, after I clear it the total field shows zero. Then, if I pick another option from group A, the values are still totaling with group B and C as if nothing was cleared.
Hope I explained that clearly, here's what I have:
<html>
<head>
<script>
function doSubmit()
{
if (validateText() == false)
{
alert("Please Complete Customer Information");
return;
}
if (validateRadio() == false)
{
alert("Please Select a Case")
return;
}
if (validateRadio1() == false)
{
alert("Please Select a Monitor")
return;
}
if (validateRadio2() == false)
{
alert("Please Select a Printer")
return;
}
alert("Order Accepted. Thank you.");
return;
}
function validateText()
{
var customer = document.Form4.customer.value;
if (customer.length == 0) return false;
var address1 = document.Form4.address1.value;
if (address1.length == 0) return false;
var city = document.Form4.city.value;
if (city.length == 0) return false;
var phone = document.Form4.phone.value;
if (phone.length == 0) return false;
var email = document.Form4.email.value;
if (email.length == 0) return false;
return true;
}
function validateRadio()
{
if (document.Form1.case[0].checked) return true;
if (document.Form1.case[1].checked) return true;
if (document.Form1.case[2].checked) return true;
return false;
}
function validateRadio1()
{
if (document.Form2.screen[0].checked) return true;
if (document.Form2.screen[1].checked) return true;
if (document.Form2.screen[2].checked) return true;
if (document.Form2.screen[3].checked) return true;
return false;
}
function validateRadio2()
{
if (document.Form3.printer[0].checked) return true;
if (document.Form3.printer[1].checked) return true;
if (document.Form3.printer[2].checked) return true;
return false;
}
function doClear()
{
document.Form4.systotal.value = "0.00";
document.Form4.customer.value = "";
document.Form4.address1.value = "";
document.Form4.address2.value = "";
document.Form4.city.value = "";
document.Form4.state.value = "";
document.Form4.zip.value = "";
document.Form4.phone.value = "";
document.Form4.email.value = "";
document.Form1.case[0].checked = false;
document.Form1.case[1].checked = false;
document.Form1.case[2].checked = false;
document.Form2.screen[0].checked = false;
document.Form2.screen[1].checked = false;
document.Form2.screen[2].checked = false;
document.Form2.screen[3].checked = false;
document.Form3.printer[0].checked = false;
document.Form3.printer[1].checked = false;
document.Form3.printer[2].checked = false;
document.Form3.printer[3].checked = false;
formPics(11);
return;
}
var computerCase = 0;
var printer = 0;
var monitor = 0;
var total = 0;
function formPics(radios)
{
switch(radios)
{
case 1:
document.getElementById("pics").innerHTML = "<img src='C1_Game.jpg'>";
computerCase = 600.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 2:
document.getElementById("pics").innerHTML = "<img src='C2_Home.jpg'>";
computerCase = 500.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 3:
document.getElementById("pics").innerHTML = "<img src='C3_Mini.jpg'>";
computerCase = 400.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 4:
document.getElementById("pics2").innerHTML = "<img src='S1_27.jpg'>";
monitor = 350.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 5:
document.getElementById("pics2").innerHTML = "<img src='S2_19.jpg'>";
monitor = 250.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 6:
document.getElementById("pics2").innerHTML = "<img src='S3_17.jpg'>";
monitor = 150.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 7:
document.getElementById("pics2").innerHTML = "<img src='S4_Proj.jpg'>";
monitor = 650.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 8:
document.getElementById("pics3").innerHTML = "<img src='P1_Ink.jpg'>";
printer = 50.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 9:
document.getElementById("pics3").innerHTML = "<img src='P2_Laser.jpg'>";
printer = 80.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 10:
document.getElementById("pics3").innerHTML = "<img src='P3_Color.jpg'>";
printer = 100.00;
total = computerCase + printer + monitor;
document.Form4.systotal.value = total;
break;
case 11:
computerCase = 0;
printer = 0;
monitor = 0;
total = 0;
break;
}
}
function totalclear()
{
if(printer > 0)
printer = 0;
return printer;
}
</script>
<style>
table{ width:800px}
#pics{ float: right;}
#pics2{ float: right;}
#pics3{ float: right;}
</style>
</head>
<body>
<h1 align="center">New System Order Form</h1>
<table border="1" cellpadding="5" align="center">
<tr>
<td>
<form name="Form1" align="left">
<h3>Choose a Case:</h3><div id='pics'></div>
<input name="case" type="radio" onClick='formPics(1)'>Gaming Behemoth ($600.00)<br/>
<input name="case" type="radio" onClick='formPics(2)'>Basic Home Computing ($500.00) <br/>
<input name="case" type="radio" onClick='formPics(3)'>Mini Entertainment Center ($400.00)<br/>
</form>
<br/>
<form name="Form2">
<h3>Choose a Monitor:</h3><div id='pics2'></div>
<input name="screen" type="radio" onClick='formPics(4)'>27" UHD LED ($350.00)<br/>
<input name="screen" type="radio" onClick='formPics(5)'>19"HD LCD ($250.00)<br/>
<input name="screen" type="radio" onClick='formPics(6)'>17"HD LCD ($150.00)<br/>
<input name="screen" type="radio" onClick='formPics(7)'>HD Laser Projector ($650.00) <br/>
</form>
<br/>
<form name="Form3">
<h3>Choose a Printer:</h3><div id='pics3'></div>
<input name="printer" type="radio" onClick='formPics(8)'>Inkjet Printer ($50.00) <br/>
<input name="printer" type="radio" onClick='formPics(9)'>Laser Printer ($80.00)<br/>
<input name="printer" type="radio" onClick='formPics(10)'>Color Laser Printer ($100.00)<br/>
</form>
</td>
<form name="Form4">
<td>
<h3 align="left">System Total: $ <input type="text" name="systotal" size="10" readonly = "readonly" value = "0.00" /></h3>
<hr style="width:100%" />
<h3 align="left">Customer Information:</h3>
<b>Full Name:</b><br/>
<input name="customer" size="45" type="text"><br/>
<b>Address:</b><br/>
<input name="address1" size="45" type="text"><br/>
<input name="address2" size="45" type="text"><br/>
<b>City, State, and Zip:</b><br/>
<input name="city" size="15 type="text">
<input name="state" size="2" type="text">
<input name="zip" size="5" type="text"><br/>
<b>Phone:</b><br/>
<input name="phone" size="40" type="text"><br/>
<b>Email:</b><br/>
<input name="email" size="40" type="text"><br/>
</form>
<hr style="width:100%" />
<br/>
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" Value="Reset Order" onClick="doClear()">
</td>
</tr>
</table>
</body>
</html>
You only have three printers, but you try to clear four. The code in the function doClear gives this error message:
TypeError: document.Form3.printer[3] is undefined
As the code crashes there, the call to formPics(11) is never executed, so the variables are never cleared.
Related
I am doing an assignemnt for school to showcase our knowledge of javascript. It is doing everything I want it to except when I adjust the first input from an empty string to a value it still has the display of first name required. I was also wondering if anyone had insight as to how to display the needed inputs when the other buttons I have clicked are cliked as I don't want the other functions to run unless all inputs are filled in the form. Thanks!
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t2result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
//Function to validate form inputs
function validate() {
var fname = document.getElementById("t1").value;
var lname = document.getElementById("t2").value;
var phoneNumber = document.getElementById("t3").value;
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var isValid = true;
if (fname == "") {
document.getElementById("t1result").innerHTML = " First Name is required";
isValid = false;
} else {
document.getElementById("t1result").innerHTML = "";
}
if (lname == "") {
document.getElementById("t2result").innerHTML = " Last Name is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (phoneNumber == "") {
document.getElementById("t3result").innerHTML = " Phone number is required";
isValid = false;
} else {
document.getElementById("t3result").innerHTML = "";
}
if (prodOne == "") {
document.getElementById("t4result").innerHTML = " Product 1 is required";
isValid = false;
} else {
document.getElementById("t4result").innerHTML = "";
}
if (prodTwo == "") {
document.getElementById("t5result").innerHTML = " Product 2 is required";
isValid = false;
} else {
document.getElementById("t5result").innerHTML = "";
}
if (prodThree == "") {
document.getElementById("t6result").innerHTML = " Product 3 is required";
isValid = false;
} else {
document.getElementById("t6result").innerHTML = "";
}
}
//Function to calculate cost of all 3 products prior to tax
function calculate() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
document.getElementById('totalAmount').innerHTML = "The total cost of the three products before tax is: $" + totalCost;
}
//Function to calculate cost of all 3 products with tax
function taxIncluded() {
var prodOne = document.getElementById("t4").value;
var prodTwo = document.getElementById("t5").value;
var prodThree = document.getElementById("t6").value;
var totalCost = parseInt(prodOne) + parseInt(prodTwo) + parseInt(prodThree)
var totalCostTaxed = parseFloat(totalCost) * 0.13 + parseFloat(totalCost)
document.getElementById('totalAmountTax').innerHTML = "The total cost of the three products with tax is: $" + totalCostTaxed;
}
<form id="f1" method="get" action="secondpage.html">
First Name: <input type="text" id="t1"><span class="result" id="t1result"></span>
<br><br> Last Name: <input type="text" id="t2"><span class="result" id="t2result"></span>
<br><br>Phone Number: <input type="text" id="t3"><span class="result" id="t3result"></span>
<br><br>Product 1 amount: <input type="text" id="t4"><span class="result" id="t4result"></span>
<br><br>Product 2 amount: <input type="text" id="t5"><span class="result" id="t5result"></span>
<br><br>Product 3 amount: <input type="text" id="t6"><span class="result" id="t6result"></span>
<br><br><input type="button" id="btn1" value="Validate" onclick="validate()">
<br><br><input type="button" id="btn1" value="Calculate" onclick="calculate()">
<br><br><input type="button" id="btn1" value="Calculate with Tax" onclick="taxIncluded()">
<div>
<p id="totalAmount">Total Amount</p>
</div>
<div>
<p id="totalAmountTax">Tax</p>
</div>
</form>
you were getting wrong element in your function validate in first condition , in else condition you were getting t2result instead of t1, hope this will work now.
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.
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>
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;
}
The submit button seems to not be running the code from what I can tell, but I'm not sure if that is what is wrong with the code. Spent a long time trying to figure it out, but still have no idea. The forms and everything seem to be right, but when I click submit the only thing that happens is that the form entries disappear and the button seems to just reset the form. In html testers it says that the file is not found so I have no clue on what I should do to debug this particular issue.
<html>
<title>Assignment 5</title>
<body>
<form>
<h2>Step 1: Enter your name, address, etc.</h2>
<formid="Computerparts">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
City: <input type="text" name="city"> State: <input type ="text" name="state"> Zip: <input type="text" name="zipcode"><br>
Phone: <input type="text" name="phonenumber"><br>
Email: <input type="text" name="email"><br>
<h2>Step 2: Select the computer components you want</h2>
CPU: <input type="radio" name="cpu"> Intel 2.0 GHz <input type="radio" name="cpu"> Intel 2.2 GHz <input type="radio" name="cpu"> Intel 3.0 GHz<br>
RAM: <input type="radio" name="ram">SIMM 1 GB <input type="radio" name="ram">SIMM 2 GB <input type="radio" name="ram" value="75">SIMM 4 GB<br>
HDD: <input type="radio" name="hdd"> IDE 60 GB<input type="radio" name="hdd"> IDE 120 GB<input type="radio" name="hdd"> IDE 250 GB<br>
<h2>Step 3: Select the optional Software you want</h2>
<form>
<input type="checkbox" name="software" value="25">Adobe Creative Suite 4<br>
<input type="checkbox" name="software">Microsoft Office 2007<br>
<input type="checkbox" name="software">Symantec Antivirus 2010<br>
<input type="submit" value = "submit" onclick="doSubmit()" /><button type="reset" value="Reset">Clear Entries</button>
</form>
<script>
function doSubmit(){
formTest = document.getElementById("Computerparts");
if(formTest.fname.value == ""){
alert("Name can not be empty");
formTest.name.focus();
return;
}
if(formTest.city.value == ""){
alert("City can not be empty");
formTest.city.focus();
return;
}
if(formTest.state.value.length != 2){
alert("state must be 2 letters");
formTest.state.focus();
return;
}
if(formTest.zip.value.length != 5){
alert("zip must be 5 digits");
formTest.zip.focus();
return;
}
if(formTest.phone.value == ""){
alert("Phone can not be empty");
formTest.phone.focus();
return;
}
if(formTest.email.value == ""){
alert("Email can not be empty");
formTest.email.focus();
return;
}
if(formTest.lname.value == ""){
alert("Last name can not be empty");
formTest.lnamel.focus();
return;
}
var checkcpu = false;
for(var i=0; i<formTest.cpu.length; i++){
if(formTest.cpu[i].checked)
checkcpu = true;
}
if(checkcpu == false){
alert("Must Choose CPU");
return;
}
var pricecpu = 0;
if(formTest.cpu[0].checked)
price = 100;
else if(formTest.cpu[1].checked)
price = 120;
else if(formTest.cpu[2].checked)
price = 150;
var checkram = false;
for(var i=0; i<formTest.ram.length; i++){
if(formTest.ram[i].checked)
checkram = true;
}
if(checkram == false){
alert("Must Choose RAM!");
return;
}
var priceram = 0;
if(formTest.ram[0].checked)
price = 25;
else if(formTest.ram[1].checked)
price = 50;
else if(formTest.ram[2].checked)
price = 75;
var checkhdd = false;
for(var i=0; i<formTest.hdd.length; i++){
if(formTest.hdd[i].checked)
checkhdd = true;
}
if(checkhdd == false){
alert("Must Choose HDD!");
return;
}
var pricehdd = 0;
if(formTest.hdd[0].checked)
price = 60;
else if(formTest.hdd[1].checked)
price = 100;
else if(formTest.hdd[2].checked)
price = 200;
for(var i=0; i<formTest.software.length; i++){
if(formTest.software[i].checked)
price += 25;
}
var price = pricehdd + priceram + pricecpu
alert("Order Submitted , Total: " + price);
}
</script>
</body>
</html>
The way to validate a form is to use the form's submit event and return false if error, true if ok = also where is your action? If no action the page will be submitted to itself:
<form id="computerparts" onsubmit="return doSubmit(this)" action="???">
remove the invalid tag formid and the onclick="doSubmit()" from the submit button and use
function doSubmit(formTest) {
// formTest = document.getElementById("Computerparts"); remove this
if(formTest.fname.value == ""){
alert("Name can not be empty");
formTest.name.focus();
return false; // return false when error
}
.
.
.
return true; // allow submit
}