Implementing Submit action in javascript - javascript

I am new to javascript..I am facing some problems while trying to implement form submit action onclick using javascript..
The problem is when I implement all the validation checks using if-else conditions ..The function dose not produce any result..
[] 1[]2
I have implemented various validation check and tried to capture all possible form elements with different conditions..But I am failing when I am implementing validation check..otherwise the code works -I cannot figure out what is the problem..
Here is the code:
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNAN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNAN(ag) || ag.parseInt() > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
</head>
<body style="background:pink;">
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>

The first error is at these lines
var nam=document.getElementById("student_name").value;
if(nam.value.length==0 || !(isNAN(nam)) || nam.value.length>20){
nam="Invalid";
}
nam is the value of the input again doing nam.value will throw an error
Secondly isNAN is not a javascript inbuilt function. Case matters while using in build function , it has to be isNaN
Thirdly ag.parseInt() is wrong. Instead it has to be parseInt(ag,10) where 10 is the radix
function submitForm() {
var nam = document.getElementById("student_name").value;
if (nam.length == 0 || !(isNaN(nam)) || nam.length > 20) {
nam = "Invalid";
}
var ag = document.getElementById("student_age").value;
if (ag.length == 0 || isNaN(ag) || parseInt(ag, 10) > 100) {
age = "Invalid";
}
var gender = document.getElementById("g1").value;
if (document.getElementById("g1").checked) {
gender = document.getElementById("g1").value;
} else if (document.getElementById("g2").checked) {
gender = document.getElementById("g1").value;
} else {
alert("You must select a gendrer!!");
}
var cty = document.getElementById("city").value;
var pan = document.getElementById("h1").value;
var dan = document.getElementById("h2").value;
var sprt = document.getElementById("h3").value;
if (document.getElementById("h1").checked) {
var pan = document.getElementById("h1").value;
pan = pan + "#";
} else {
pan = "";
}
if (document.getElementById("h2").checked) {
var dan = document.getElementById("h2").value;
dan = dan + "#";
} else {
dan = "";
}
if (document.getElementById("h3").checked) {
var sprt = document.getElementById("h3").value;
sprt = sprt + "#";
} else {
spt = "";
}
var hobbies = pan + "" + dan + "" + sprt
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
}
<div id="body">
<form>
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label> <input type="checkbox" id="h1" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
</form>
<input type="submit" value="Submit" id="student_submit" onclick="submitForm()">
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>

This might help you
function submitForm()
{
var nam = document.getElementById("student_name").value;
if (!(nam) || nam.length > 20)
{
alert("please Select a valid name");
return false;
}
var ag = document.getElementById("student_age").value;
if (!(ag) || ag > 100)
{
alert("please Select a valid age");
return false;
}
var gender = "";
if(!document.getElementById("g1").checked && !document.getElementById("g2").checked )
{
alert("please Select gender");
return false;
}
else
{
if(document.getElementById("g1").checked)
{
gender = document.getElementById("g1").value;
}
else
{
gender = document.getElementById("g2").value;
}
}
var cty = document.getElementById("city").value;
if (!(cty) || cty=="Default")
{
alert("please Select a city");
return false;
}
var hobbies ="";
if(!document.getElementById("h1").checked && !document.getElementById("h2").checked && !document.getElementById("h3").checked)
{
alert("please Select hobby");
return false;
}
else
{
var inputElements = document.getElementsByName("cbox");
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
var value=" "+ inputElements[i].value;
hobbies +=value;
}
}
}
document.getElementById("name").innerHTML = nam; //document.getElementById("student_name").value;
document.getElementById("age").innerHTML = ag; //document.getElementById("student_age").value;
document.getElementById("gd").innerHTML = gender;
document.getElementById("ct").innerHTML = cty; //document.getElementById("city").value;
document.getElementById("hb").innerHTML = hobbies; //document.getElementById("h1").value;
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MyTest</title>
<script type="text/javascript" src="index.js"></script>
</head>
<body style="background:pink;">
<div id="body">
<form action="#" method="post" onsubmit="return false">
<br><br>
<span id="name_label" style="background:yellow;">Student Name</span> <input type="text" id="student_name" style="background:yellow;"> <br><br>
<span id="age_label" style="background:yellow;">Age</span> <input type="text" id="student_age" style="background:yellow;"><br><br> Gender <input type="radio" value="male" name="gender" id="g1">M
<input type="radio" value="female" name="gender" id="g2">F<br>
<br><br> City
<select id="city">
<option value="Default">Select City</option>
<option value="Delhi">Delhi</option>
<option value="Mumbai">Mumbai</option>
<option value="Kolkata">Kolkata</option>
<option value="Chennai">Chennai</option>
</select><br><br>
<label>Hobby </label>
<input type="checkbox" id="h1" name="cbox" value="Painting">Painting
<input type="checkbox" id="h2" name="cbox" value="Dancing">Dancing
<input type="checkbox" id="h3" name="cbox" value="Sports">Singing
<br><br>
<input type="submit" value="Submit" onclick="submitForm()">
</form>
<div>
<label>Name:</label><span id="name"></span><br>
<label>Age:</label><span id="age"></span><br>
<label>Gender:</label><span id="gd"></span><br>
<label>City:</label><span id="ct"></span><br>
<label>Hobbies:</label><span id="hb"></span><br>
</div>
</div>
</body>
</html>

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/

At least one radio and checkbox must be select in JavaScript

how to validate all the section by at least choose one option. with my code, it just show the first "please select 1". so how to edit the code to show the all requirement like "pls choose at least one" at beside the section or below the submit button. I'm just a beginner, now learning for JavaScript. You are prefer to done with some code editor, to have a better understand for beginner. Here is my code :
var person = [];
person["person1"]=1;
person["person2"]=2;
person["person3"]=3;
person["person4"]=4;
person["person5"]=5;
var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100*454.58;
elec["elec2"] = 200*454.58;
elec["elec3"] = 300*454.58;
elec["elec4"] = 400*454.58;
elec["elec5"] = 500*454.58;
elec["elec6"] = 600*454.58;
elec["elec7"] = 700*454.58;
elec["elec8"] = 800*454.58;
elec["elec9"] = 900*454.58;
function getNumberperson()
{
var numberperson=0;
var theForm = document.forms["energyform"];
var selectedPerson = theForm.elements["selectedperson"];
for(var i = 0; i < selectedPerson.length; i++)
{
if(selectedPerson[i].checked)
{
numberperson = person[selectedPerson[i].value];
}
}
return numberperson;
}
function getElectotal()
{
var electotal=0;
var theForm = document.forms["energyform"];
var selectedElec = theForm.elements["electricity"];
electotal = elec[selectedElec.value];
return electotal;
}
function recyclealu()
{
var recyclealu=0;
var theForm = document.forms["energyform"];
var yesalu = theForm.elements["yesalu"];
if(yesalu.checked==true)
{
recyclealu=-89.38;
}
return recyclealu;
}
function recycleplas()
{
var recycleplas=0;
var theForm = document.forms["energyform"];
var yesplas = theForm.elements["yesplas"];
if(yesplas.checked==true)
{
recycleplas=-35.56;
}
return recycleplas;
}
function checkAllRecycles() {
const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');
if (recycleBoxes) {
recycleBoxes.forEach((recycleBox) => {
if (!recycleBox.checked) {
recycleBox.checked = 'checked';
}
})
}
calculateTotal();
}
function calculateTotal()
{
var totalco = getNumberperson()*getElectotal() + recyclealu() + recycleplas();
//display the result
document.getElementById('totalConsumption').innerHTML = +totalco;
}
//add a function to hide the result on page loading at the start
function hideTotal()
{
document.getElementById('totalConsumption').innerHTML = "0";
}
function vpeople()
{
var cp = document.getElementsByName('selectedperson');
for (var i = 0; i < cp.length; i++)
{
if (cp[i].type == 'radio')
{
if (cp[i].checked) {return true}
}
}
return false;
}
function velec()
{
var ce = document.getElementsByName('electricity');
for (var i = 0; i < ce.length; i++)
{
if (ce[i].type == 'radio')
{
if (ce[i].checked) {return true}
}
}
return false;
}
function vrcyalu()
{
var crcyalu = document.getElementsByName('yesalu');
for (var i = 0; i < crcyalu.length; i++)
{
if (crcyalu[i].type == 'checkbox')
{
if (crcyalu[i].checked) {return true}
}
}
return false;
}
function vrcyplas()
{
var crcyplas = document.getElementsByName('yesalu');
for (var i = 0; i < crcyplas.length; i++)
{
if (crcyplas[i].type == 'checkbox')
{
if (crcyplas[i].checked) {return true}
}
}
return false;
}
function allvalidate()
{
if(!vpeople())
{
alert("Please select1");
return false;
}
return true;
if(!vwaste())
{
alert("Please select2");
return false;
}
return true;
if(!velec())
{
alert("Please select3");
return false;
}
return true;
if(!vrcyalu())
{
alert("Please select4");
return false;
}
return true;
if(!vrcyplas())
{
alert("Please select5");
return false;
}
return true;
checkAllRecycles;
}
<body onload='hideTotal()'>
<div id="all">
<form action="/action_page.php" id="energyform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Carbon Footprint Calculator</legend>
<label >Number of Person Live in Household</label><br/>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person1" onclick="calculateTotal()" />1&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person2" onclick="calculateTotal()" />2&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person3" onclick="calculateTotal()" />3&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person4" onclick="calculateTotal()" />4&nbsp</label>
<label class='radiolabel'><input type="radio" name="selectedperson" value="person5" onclick="calculateTotal()" />5&nbsp</label>
<br/><br/>
<label><i class="fa fa-flash"></i>Energy Consumption Per Month</label>
<br/>
<label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
<select id="electricity" name='electricity' onchange="calculateTotal()">
<option value="elecuse">0</option>
<option value="elec1">100</option>
<option value="elec2">200</option>
<option value="elec3">300</option>
<option value="elec4">400</option>
<option value="elec5">500</option>
<option value="elec6">600</option>
<option value="elec7">700</option>
<option value="elec8">800</option>
<option value="elec9">900</option>
</select>
<br/><br/>
<label><i class="fa fa-flash"></i>Recycle </label>
<br/>
<label for='yesalu' class="alu">&nbspAluminium and Steel&nbsp&nbsp</label>
<input type="checkbox" id="yesalu" name='yesalu' onclick="calculateTotal()" />
<br/>
<label for='yesplas' class="plas">&nbspPlastic&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
<input type="checkbox" id="yesplas" name='yesplas' onclick="calculateTotal()" />
<br/>
<button type="button" onclick="checkAllRecycles()">Select All</button>
<br/>
<p>Total CO2 produced per year per household:</p>
<div id="totalConsumption">0</div>
</fieldset>
</div>
<input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
<input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
</div>
</form>
</div>
</body>
thx you very much for helping me, stay safe.
hello please check this page :
https://stackoverflow.com/questions/13060313/checking-if-at-least-one-radio-button-has-been-selected-javascript

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.

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

Form Validation?

I'm just trying to make this check form validation. Like it shouldn't let the form submit unless everything is filled in, then it should do the total only if it works. I'm new to this and I have no idea what is going on, but it is just showing a blue box at the top of my screen by default, and then submitting/accepting regardless of the form being filled out or not.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hands-on Project 6 - Order</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<section>
<article>
<h2>Pizza Order Form</h2>
<div id="errorMessage">
</div>
<form action="results.html" id="orderForm">
<input type="hidden" name="hidden" id="hidden">
<fieldset>
<legend>Delivery Information</legend>
<label for="nameinput">Name</label>
<input type="text" id="nameinput" name="name">
<label for="addrinput">Street Address</label>
<input type="text" id="addrinput" name="address">
<label for="cityinput">City</label>
<input type="text" id="cityinput" name="city">
<label for="emailinput">Email</label>
<input type="email" id="emailinput" name="email">
<label for="phoneinput">Phone</label>
<input type="tel" id="phoneinput" name="phone">
</fieldset>
<fieldset>
<legend>Order</legend>
<p>
<span class="nonLabel">What type of crust:</span>
<br>
<input type="radio" name="crust" id="thin" value="1">
<label for="thin">Thin Crust</label>
<input type="radio" name="crust" id="original" value="0">
<label for="original">Original Crust</label>
<input type="radio" name="crust" id="thick" value="3">
<label for="thick">Deep Dish</label>
</p>
<label for="size" class="nonLabel">What size pizza:</label>
<select id="size" name="size">
<option value=""> </option>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="XL">Extra Large</option>
</select>
<p>
<span class="nonLabel">What topping(s):</span>
<br>
<input type="checkbox" id="pepperoni" name="toppings" value="Pepperoni">
<label for="pepperoni">Pepperoni</label>
<input type="checkbox" id="sausage" name="toppings" value="Sausage">
<label for="sausage">Sausage</label>
<input type="checkbox" id="bacon" name="toppings" value="Bacon">
<label for="bacon">Bacon</label>
<br>
<input type="checkbox" id="greenpep" name="toppings" value="Green Peppers">
<label for="greenpep">Green Peppers</label>
<input type="checkbox" id="onion" name="toppings" value="Onions">
<label for="onion">Onions</label>
<input type="checkbox" id="xcheese" name="toppings" value="Extra Cheese">
<label for="xcheese">Extra Cheese</label>
</p>
<p>
<label for="instructions" id="instrlabel">Special Instructions:</label>
</p>
<textarea id="instructions" name="instructions" rows="3" cols="60"
placeholder="Special Requests, Delivery Details"></textarea>
</fieldset>
<fieldset id="submitbutton">
<input type="submit" id="submitBtn" value="Add to Cart">
</fieldset>
</form>
</article>
</section>
<script>
document.getElementById("submitBtn ").addEventListener("submit",
validateForm(evt));
</script>
</body>
</html>
JavaScript:
// validate required fields
function validateForm(evt){
if(evt.preventDefault){
evt.preventDefault();
}
else {
evt.returnValue = false;
}
formValidity = true;
validateFormControls();
}
function validateFormControls(){
var inputElements = document.querySelectorAll("fieldset:first-of-type
input");
var errorDiv = document.getElementById("errorMessage");
var crustBoxes = document.getElementsByName("crust");
var fieldsetValidity = true;
var elementCount = inputElements.length;
var currentElement;
try {
for(var i = 0; i < elementCount; i++){
currentElement = inputElements[i];
if(currentElement.value === ""){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else {
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
}
currentElement.querySelectorAll("select")[0];
if (currentElement.selectedIndex === 0){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else{
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
if (!crustBoxes[0].checked && !crustBoxes[1].checked &&
!crustBoxes[2].checked){
crustBoxes[0].style.outline = "3px solid #0B907A";
crustBoxes[1].style.outline = "3px solid #0B907A";
crustBoxes[2].style.outline = "3px solid #0B907A";
}
else {
crustBoxes[0].style.outline = "";
crustBoxes[1].style.outline = "";
crustBoxes[2].style.outline = "";
}
if (fieldsetValidity === false){
throw "Please complete all required fields.";
}
else {
errorDiv.style.display = "none";
errorDiv.innerHTM = "";
}
catch(msg){
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
formValidity = false;
}
}
}
function orderTotal(){
var itemTotal = 5;
var crusts = document.getElementsByName("crust");
var toppings = document.getElementsByName("goodnight");
var sizes = document.querySelectorAll("select")[0];
if (sizes.selectedIndex > 0) {
itemTotal += ((sizes.selectedIndex * 1) * 2);
}
for (var i=0; i < toppings.length; i++){
if (toppings[i].checked) {
itemTotal += 1;
}
}
for (var i=0; i < crusts.length; i++){
if (crusts[i].checked) {
itemTotal += (crusts[i].value * 1);
}
}
alert ("Your order total is $" + itemTotal);
document.getElementById("hidden").value = itemTotal;
}
Wrong id parameter
document.getElementById("submitButton ").addEventListener("submit", validateForm(evt));
Must be
document.getElementById("submitBtn").addEventListener("submit",validateForm(evt));

Categories

Resources