How do I make error messages show on the webpage? [duplicate] - javascript

This question already has answers here:
HTML5 form required attribute. Set custom validation message?
(17 answers)
Closed 1 year ago.
function validate() {
var errMsg = "";
var result = true;
var fname = document.getElementById("fname").value;
if (!fname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your first name correctly.\n";
result = false;
}
var lname = document.getElementById("lname").value;
if (!lname.match(/^[a-zA-Z]+$/)) {
errMsg += "Please enter your last name correctly.\n";
result = false;
}
var email = document.getElementById("email").value;
if (!email.match(/[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,}$/)) {
errMsg += "Please enter your email correctly.\n";
result = false;
}
var streetname = document.getElementById("streetname").value;
if (!streetname.match(/^[a-zA-Z0-9\s]+$/)) {
errMsg += "Please enter your street name correctly.\n";
result = false;
}
var suburb = document.getElementById("suburb").value;
if (!suburb.match(/^[a-zA-Z\-]+$/)) {
errMsg += "Please enter your suburb correctly.\n";
result = false;
}
var phone = document.getElementById("phone").value;
if (!phone.match(/[0-9]{9}/)) {
errMsg += "Please enter your phone number correctly.\n";
result = false;
}
var gender = document.getElementById("gender").value;
var start = document.getElementById("start").value;
var skill = document.getElementById("skill").value;
var other = document.getElementById("other").value;
var otherbox = document.getElementById("otherbox").value;
var postcode = document.getElementById("postcode").value;
var state = document.getElementById("state").options[
document.getElementById("state").selectedIndex
].text;
var regex;
//VIC = 3 OR 8, NSW = 1 OR 2 ,QLD = 4 OR 9 ,NT = 0 ,WA = 6 ,SA=5 ,TAS=7 ,ACT= 0.
switch (state) {
case "Please Select":
return false;
case "VIC":
regex = new RegExp(/(3|8)\d+/);
break;
case "NSW":
regex = new RegExp(/(1|2)\d+/);
break;
case "QLD":
regex = new RegExp(/(4|9)\d+/);
break;
case "NT":
regex = new RegExp(/0\d+/);
break;
case "WA":
regex = new RegExp(/6\d+/);
break;
case "SA":
regex = new RegExp(/5\d+/);
break;
case "TAS":
regex = new RegExp(/7\d+/);
break;
case "ACT":
regex = new RegExp(/0\d+/);
break;
}
if (!postcode.match(regex)) {
errMsg = errMsg + "State and postcode do not match\n";
result = false;
}
if (errMsg) {
alert(errMsg);
}
if (result) {
storeBooking(
fname,
lname,
start,
email,
gender,
phone,
streetname,
suburb,
state,
postcode,
other,
otherbox
);
}
return result;
}
<form action="https://mercury.swin.edu.au/it000000/formtest.php" method="post" id="regform">
<p>Your Name: <span id="job1"></span></p>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Your name.." required="required" maxlength="25" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" placeholder="Your last name.." required="required" onkeypress="return (event.charCode > 64 && event.charCode < 91) || (event.charCode > 96 && event.charCode < 123) || (event.charCode==32)">
<label for="start">Date of birth:</label>
<input type="date" id="start" required="required" name="date of birth" value="2021-10-04" />
<br>
<br>
<label for="gender"> Select you gender</label>
<br>
<br>
<select name="gender" id="gender" required="required">
<option value="" selected>Please Select</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label for="streetname">Street Address</label>
<input type="text" id="streetname" name="streetname" required="required" placeholder="Your street name..." maxlength="40" />
<label for="suburb">Suburb/Town</label>
<input type="text" id="suburb" name="suburb" required="required" placeholder="Your suburb/town..." maxlength="40">
<label for="state">Choose a state:</label>
<br>
<select name="state" id="state" required="required">
<option value="">Please Select</option>
<option value="VIC">VIC</option>
<option value="NSW">NSW</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="TAS">TAS</option>
<option value="ACT">ACT</option>
</select>
<br>
<br>
<label for="postcode">Postcode</label>
<input type="text" id="postcode" name="postcode" required="required" placeholder="Your postcode..." maxlength="4" minlength="4" pattern="^[0-9]{4}$">
<label for="email">Email Address</label>
<input type="text" id="email" name="emailadd" placeholder="Your email address.." required="required">
<label for="phone">Phone Number</label>
<input type="text" id="phone" name="phonenumb" placeholder="e.g. 0451124561" minlength="8" maxlength="12" required="required">
<br>
<input type="submit" value="Apply">
<br>
<br>
<input type="submit" id="cancelpurchase" value="Cancel Application"></input>
</form>
How do I make it so that the error message shows up on the actual webpage, rather than an alert box, next to the input? I can't seem to find anything online about changing the default way an error message shows up. If you need less/more information, please suggest that to me.
Note: no jQuery or inline JavaScript.

You can make a <div id="popup"> Error message </div> with display: none and position: fixed and instead of alertion make this div visible document.querySelector('#popup').style.display = 'block' and a close button in it to close this popup

You appear to be showing the error message with the following code:
if (errMsg) {
alert(errMsg);
}
If you instead get a reference to an element,
e.g
var tgtElem = document.getElementById(textStringIdGoesHere);
You can then display the message by setting its textContent,
e.g
tgtElem.textContent = errMsg;

Related

Disabling a button on empty <select> list?

`I've created a form that allows a user to enter their details and have their first and last names displayed along with a numerical ID. There is a 'Delete' button allowing the user to remove whatever name they select.
by default, the 'Delete' button should be disabled until the <select> list is populated. If all names are deleted from the list - the 'Delete' button should disable again.
That's where im struggling. I cant get the 'Delete' button to enable when a name is added to the list.
Below is my HTML and JavaScript:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.value === 1;
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log("is remove being triggered??")
}
if (Member.options.length == ""){
Delete.disabled = true
}
else {
Delete.disabled = false
}
</script>
</body>
`
The reason why the Delete button is not enabling is because the code that is supposed to enable the Delete button is only run once, when the page loads.
Assuming that this is the code that is supposed to enable the button:
if (Member.options.length == 0){ // changed from Member.options.length == ""
Delete.disabled = true
} else {
Delete.disabled = false
}
This code is only run once, when the page loads and the JavaScript code is run. In order to enable the button properly, we need to run this code every time that Member.options.length changes. One way you can do this is place the code snippet above for disabling/enabling the Delete button inside the onclick listener for the save button and to re-check every time a new user is saved. You would have to add this snippet into every place in your code where Member.options.length could change (inside the listener for the delete button as well).
Full updated code:
MemberList
<h1>Member List</h1>
<form method="post" id="_frmFull">
<label for="lstMembers">Member:</label>
<select size="10"
name="lstMembers"
id="lstMembers">
</select>
<button type="button"
id="addMember"
name="Add Member">
Add Member
</button>
<button type="button"
name="Delete Member"
id="delete">
Delete Member</button>
<div id="Modal" class="modal">
<div class="modal-form">
<label for="memTitle">Title:</label>
<input list="memTitles" name="memTitles" id="memTitle">
<datalist id="memTitles">
<option value="Dr">
<option value="Mr">
<option value="Mrs">
<option value="Ms">
</datalist>
<label for="firstName">First Name:</label>
<input type="text" name="firstName" id="firstName" required="required">
<label for="middleName">Middle Name (optional):</label>
<input type="text" name="middleName" id="middleName">
<label for="lastName">Last Name:</label>
<input type="text" name="lastName" id="lastName" required="required">
<br><br>
<label for="Country">Country:</label>
<input list="countries" name="Country" id="Country">
<datalist id="countries">
<option value="Australia">
<option value="United Kingdom">
<option value="America">
<option value="New Zealand">
</datalist>
<label for="Gender">Gender:</label>
<select name="Gender" id="Gender">
<option>Male</option>
<option>Female</option>
<option>Other</option>
</select>
<label for="birthDate">Birthdate:</label>
<input type="date"
id="birthDate"
min="1900-01-01"
max="2022-12-31" required="required">
<br><br>
<div id="resiAddress">
<p>Residential Address:</p>
<br>
<label for="txtResidentialAddress">Address:</label>
<input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">
<br><br>
<label for="txtResiPostCode">Postcode:</label>
<input type="text" required="required" id="txtResiPostCode">
<br><br>
<label for="txtResiSuburb">Suburb:</label>
<input type="text" required="required" id="txtResiSuburb">
<br><br>
<label for="txtResiCountry" class="country">Country</label>
<input type="text" required="required" id="txtResiCountry">
<br><br>
<label for="txtResiState">State:</label>
<input type="text" required="required" id="txtResiState">
</div>
<br><br>
<label for="chkSynchronizeAddresses">Same as residential </label>
<input type="checkbox" required="required" id="chkSynchronizeAddresses" >
<div id="postAddress">
<p>Postal Address:</p>
<br>
<label for="txtPostalAddress">Address:</label>
<input type="text" id="txtPostalAddress">
<br><br>
<label for="txtPostCode">Postcode:</label>
<input type="text" id="txtPostCode">
<br><br>
<label for="txtPostalSuburb">Suburb:</label>
<input type="text" id="txtPostalSuburb">
<br><br>
<label for="txtPostalCountry">Country:</label>
<input type="text" id="txtPostalCountry">
<br><br>
<label for="txtPostalState">State:</label>
<input type="text" id="txtPostalState">
</div>
<br><br>
<label for="txtPhone" class="phone">Phone: (optional)</label>
<input id="txtPhone" type="text">
<br><br>
<label for="txtMobile" class="mobile">Mobile: (optional)</label>
<input id="txtMobile" type="text">
<br><br>
<button type="button" name="save" id="save">Save</button>
<br><br>
<button type="button"
name="cancel"
id="closeModal">
Cancel</button>
</div>
</div>
</form>
<script>
console.log("Log test - please work!!")
const addBtn = document.getElementById("addMember");
const modal = document.getElementById("Modal");
const cancelBtn = document.getElementById("closeModal");
let chkSynchronizeAddresses = document.getElementById("chkSynchronizeAddresses");
const _frmFull = document.getElementById("_frmFull");
let Member = document.getElementById("lstMembers");
let Delete = document.getElementById("delete");
let save = document.getElementById("save");
let fName = document.getElementById("firstName");
let lName = document.getElementById("lastName");
let birthDate = document.getElementById("birthDate");
Delete.disabled = Member.options.length == 0
addBtn.onclick = function (){
openPopUp();
console.log('function - correct');
}
cancelBtn.onclick = function (){
let closeTrue = confirm("Close form? You've not saved anything.")
if (closeTrue === true) {
closePopUp();
}
}
chkSynchronizeAddresses.onclick = function (){
console.log("Is this working??");
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").setAttribute("readonly", "true");
document.getElementById("txtPostCode").setAttribute("readonly", "true");
document.getElementById("txtPostalState").setAttribute("readonly", "true");
document.getElementById("txtPostalSuburb").setAttribute("readonly", "true");
document.getElementById("txtPostalCountry").setAttribute("readonly", "true");
copyAddressFields();
}
else {
document.getElementById("txtPostalAddress").removeAttribute("readonly");
document.getElementById("txtPostCode").removeAttribute("readonly")
document.getElementById("txtPostalState").removeAttribute("readonly");
document.getElementById("txtPostalSuburb").removeAttribute("readonly");
document.getElementById("txtPostalCountry").removeAttribute("readonly");
}
}
function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById("txtPostalAddress").value = document.getElementById("txtResidentialAddress").value;
document.getElementById("txtPostCode").value = document.getElementById("txtResiPostCode").value;
document.getElementById("txtPostalSuburb").value = document.getElementById("txtResiSuburb").value;
document.getElementById("txtPostalState").value = document.getElementById("txtResiState").value;
document.getElementById("txtPostalCountry").value = document.getElementById("txtResiCountry").value;
}
}
let idCount = 0
save.onclick = function (){
let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById("txtPostalCountry").value
let pSuburbValue = document.getElementById("txtPostalSuburb").value
let pStateValue = document.getElementById("txtPostalState").value
let pCodeValue = document.getElementById("txtPostCode").value
let pAddressValue = document.getElementById("txtPostalAddress").value
if (fNameValue === ""){
alert("Please enter your first name to proceed");
return false;
}
else
if (lNameValue === "") {
alert("Please enter your last name to proceed");
return false;
} else if (bDateValue === "") {
alert("Please select a DOB to proceed");
return false;
} else if (pCountryValue === "") {
alert("Please enter your country to continue");
return false;
} else if (pSuburbValue === "") {
alert("Please enter your suburb to continue");
return false;
} else if (pCodeValue === "") {
alert("Please enter your postcode to continue");
return false;
} else if (pAddressValue === "") {
alert("Please enter your Address to continue");
return false;
} else if (pStateValue === "") {
alert("Please enter your state to continue");
return false;
} else {
Member.innerHTML +=
`<option value= >${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}<option>`
idCount++
console.log("check - is increase even working????")
if (Member.options.length == 0){
Delete.disabled = true
}
else {
Delete.disabled = false
}
}
closePopUp();
return true;
}
function closePopUp() {
modal.style.display="none";
}
function openPopUp() {
modal.style.display = "block";
}
Delete.onclick = function removeOption () {
Member.remove(Member.options);
if (Member.options.length == 0) {
Delete.disabled = true
}
else {
Delete.disabled = false
}
console.log("is remove being triggered??")
}
</script>
</body>
so if i understood correctly you want to toggle a button if a is populated
In that case you want to keep track of the options
You can use
document.querySelectoAll('options')
and store it in a variable
then write a function that check if there's a value in that variable and disable or enable the button based on that.
Here's a fiddle:
https://jsfiddle.net/skm7bcr6/15/

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

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

Why does my JavaScript file crash without any apparent errors?

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

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

I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit

trouble validating various inputs with jQuery

for a class project I have to build a website for a pet store, featuring a pet grooming service. This involves a form, php and a mysql server on my localhost. I have been unable to correctly validate this form via a jQuery validator plugin for some unknown (to me) reason.
I've had no luck via regular jQuery code beyond getting the form to not submit blank input values. So as it is, anybody can put 'sadklfhsdk' in any of the fields (except for email, unless it has a '#') and it will validate and submit to the server.
So after I going through a couple of tutorials this is what I have so far:
The HTML:
<body>
<div id="h2Groom"><h2>Grooming Request Form</h2></div>
<form id="groom_form" method="post" action="insertPS.php">
<div id="result"></div>
<label for="firstName"><span>First Name:</span>
<input type="text" name="firstName" id="firstName" placeholder="Enter Your First Name" class="required"/>
</label>
<label for="lastName"><span>Last Name:</span>
<input type="text" name="lastName" id="lastName" placeholder="Enter Your Last Name" class="required"/>
</label>
<label for="email"><span>Email Address:</span>
<span id="error"></span>
<input type="email" name="email" id="email" placeholder="Enter a Email"/>
</label>
<label for="phone"><span>Phone Number:</span>
<span id="error"></span>
<input type="text" name="phone" id="phone" placeholder="Enter a phone number" class="required"/>
</label>
<label for="address"><span>Address:</span>
<input type="text" name="address" id="address" placeholder="Enter your address" class="required"/>
</label>
<label for="city"><span>City:</span>
<input type="text" name="city" id="city" placeholder="Enter your city" />
</label>
<label for="state"><span>State:</span>
<input type="text" name="state" id="state" placeholder="Enter your state" class="required"/>
</label>
<label for="zipcode"><span>Zipcode:</span>
<input type="text" name="zipcode" id="zipcode" placeholder="Enter your zipcode" class="required"/>
</label>
<label for="petType"><span>Type of Pet:</span>
<ul>
<li><label><input name="petType" type="radio" value="dog" id="dog">Dog</label></li>
<li><label><input name="petType" type="radio" value="cat" id="cat">Cat</label></li>
<li><label><input name="petType" type="radio" value="bird" id="bird">Bird</label></li>
</ul>
</label>
<select id="breed" name="breed">
<option value="0">--Please Choose Dog Breed--</option>
<option value="AlaskanMal">Alaskan Malamute</option>
<option value="Bichon">Bichon Frise</option>
<option value="WelshCorgi">Corgi, Welsh</option>
<option value="Dalmation">Dalmation</option>
<option value="EnglishToySpan">English Toy Spaniel</option>
<option value="FrenchBull">French Bull Dog</option>
<option value="Greyhound">Greyhound</option>
<option value="Papillon">Papillon</option>
<option value="Rottweiler">Rottweiler</option>
<option value="YorkshireTerr">Yorkshire Terrier</option>
</select>
<label for="neut"><span>Check box if your pet has been neutered/spayed (leave unchecked if not).</span></label>
<ul>
<label>
<li><input type="checkbox" name="neut" id="neut" />Yes</li></label>
</ul>
<br />
<br />
<br />
<label for="petname"><span>Pet Name:</span>
<input type="text" name="petname" id="petname" placeholder="Enter your pet's name" class="required" />
</label>
<label for="petBday"><span>Pet's Birthday:</span>
<input type="date" id="petBday" name="petBday"/>
</label>
<span> </span>
<input type="submit" id="submitBttn" value="Submit" /><input type="reset" id="resetBttn" value="Reset" />
</form>
</body>
The jQUERY (except the script to send values to server, see jsfiddle link):
$(document).ready(function() {
$('input[name=petType]').click(function() {
if(this.id=='dog') {
$('#breed').show('slow');
}
else {
$('#breed').hide('slow');
}
});
$('input[name=phone]').blur(function() {
if (validatePhone('phone')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$('input[name=email]').blur(function() {
if (validateEmail('email')) {
$('#error').html('Valid');
$('#error').css('color', 'green');
}
else {
$('#error').html('Invalid');
$('#error').css('color', 'red');
}
});
$("#submitBttn").click(function() {
//get input field values
var user_firstName = $('input[name=firstName]').val();
var user_lastName = $('input[name=lastName]').val();
var user_email = $('input[name=email]').val();
var user_address = $('input[name=address]').val();
var user_phone = $('input[name=phone]').val();
var user_city = $('input[name=city]').val();
var user_state = $('input[name=state]').val();
var user_zipcode = $('input[name=zipcode]').val();
var user_petname = $('input[name=petname]').val();
var checked_radio = $('input:radio[name=petType]').is(':checked');
var user_neut = $('input:checkbox[name=neut]').is(':checked');
var user_breed = $('input:select[name=breed]').is(':selected');
var txtVal = $('#petBday').val();
if(isDate(txtVal))
alert('Valid Date');
else
alert('Invalid Date');
var proceed = true;
//Validation functions, executed when user hits "submit"
function validatePhone(phone) {
var a = document.getElementById(phone).value;
var filter = /^[0-9-+]+$/;
if (filter.text(phone)) {
return true;
}
else {
return false;
}
}
function validateEmail(email) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(email)) {
return true;
}
else {
return false;
}
}
function isDate(txtDate)
{
var currVal = txtDate;
if(currVal == '')
return false;
//declare regex
var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var dtArray = currVal.match(rxDatePattern); //is the format ok?
if(dtArray ==null)
return false;
//checks for mm/dd/yyyy format
dtMonth = dtArray[1];
dtDay = dtArray[3];
dtYear = dtArray[5];
if(dtMonth < 1 || dtMonth > 12)
return false;
else if (dtDay < 1 || dtDay > 31)
return false;
else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31)
return false;
else if (dtMonth == 2)
{
var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
if(dtDay > 29 || (dtDay ==29 && !isleap))
return false;
}
return true;
}
EDIT: corrected if(filter.text()) to if(filter.test(phone)). None of my java validation code works.
validatePhone: filter.text should be spelled test

Categories

Resources