Form Validation? - javascript

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));

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.

how to validate my input type radio in my Multistep form? When I click Next Then its forworded to next step

I am using the multistep form and I want to prevent input radio in step form if the radio is not selected then not forward another step. My input type of text is validated.
allNextBtn.click(function(e) {
e.preventDefault();
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]')
.parent()
.next()
.children("a"),
**curInputs = curStep.find(
"input[type='text'],input[type='url'],input[type='email'],input[type='phone'],input[type='date']"
),**
isValid = true;
$(".form-group").removeClass("alert alert-danger");
$(".msg_error").html("");
for (var i = 0; i < curInputs.length; i++) {
if (!curInputs[i].validity.valid) {
isValid = false;
$(curInputs[i])
.closest(".form-group")
.addClass(" alert alert-danger");
$(".msg_error").html("All fields are mandatory.");
}
//console.log(!curInputs[i].validity.valid);
}
<input type="radio" name="customer_budget" value="$0 - $15,000">
<input type="radio" name="customer_budget" value="$15,001 - $30,000">
<input type="radio" name="customer_budget" value="$30,001 - $50000">
<input type="radio" name="customer_budget" value="$50,001 - Above">
function getSelectedRadioValue(name) {
var radios = document.getElementsByName(name);
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return radios[i].value;
}
}
}
function result() {
var score = 0;
score += parseInt(getSelectedRadioValue("q1")) || 0;
score += parseInt(getSelectedRadioValue("q2")) || 0;
score += parseInt(getSelectedRadioValue("q3")) || 0;
score += parseInt(getSelectedRadioValue("q4")) || 0;
document.getElementById('result').innerHTML = ("You selected " + score);
document.getElementById("questions").style.display = 'none';
document.getElementById('result').style.display = 'block';
}
window.onload = function() {
check.onclick = result;
}
<body>
<div class="topnav">
</div><br><br>
<div class="center123">
<br>
<div id="questions" class="divhide">
<div class="divh2">
<b>1) What is the square root of 64?</b>
<div class="answers"><br>
<label class="radiobox">
<input class="radio" type="radio" value="9000" name="q1">9000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="60000" name="q2">60000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="8000" name="q3">8000
</label>
<br><br><br>
<label class="radiobox">
<input class="radio" type="radio" value="12000" name="q4">12000
</label>
<br><br><br>
</div>
</div>
<br>
<input type="hidden" name="jq1" id="jq1" />
<input class="button" type="button" id="check" value="SUBMITT">
<font align="center" size="10" color="black">
</div>
<p id="result" style="display:none;">Result</p>
</font><br>
Next Step
</body>
Try this

javascript code when multiple checkboxes are checked form fields should appear according to the checkboxes(i tried this using select option method)

Need check-boxes instead of selection option and multiple check for check boxes according to the checked check boxes form fields should appear.
with a submit button. i have added css a small part, need a full detailed css for this case.
function showHide(elem) {
if(elem.selectedIndex != 0) {
//hide the divs
for(var i=0; i < divsO.length; i++) {
divsO[i].style.display = 'none';
}
//unhide the selected div
var y = document.getElementsByClassName('input'+elem.value);
for (var i = 0; i < y.length; i++) {
y[i].style.display = 'block';
}
}
}
window.onload=function() {
//get the divs to show/hide
divsO = document.getElementById("main-form").getElementsByTagName('input');
}
#main-form input {
display: none;
}
.common {
margin-bottom: 8px;
}
<head>
<title></title>
</head>
<body>
<form id="main-form">
<select onchange="showHide(this)" id="select-field">
<option value="">Select an option</option>
<option value="1">flight</option>
<option value="2">hotel</option>
<option value="3">travel</option>
</select>
<br><br>
<input type="text" class="input1 common" placeholder="flight">
<input type="text" class="input1 common" placeholder="flight2">
<input type="text" class="input1 common" placeholder="flight3">
<input type="text" class="input2 common" placeholder="hotel">
<input type="text" class="input2 common" placeholder="hotel2">
<input type="text" class="input3 common" placeholder="travel">
<input type="text" class="input3 common" placeholder="travel2">
<input type="text" class="input3 common" placeholder="travel3">
<input type="text" class="input3 common" placeholder="travel4">
</form>
<span id="show"></span>
Every time a checkbox is clicked, it triggers a toggle function which will either hide or show its corresponding textbox inputs.
function toggle(object){
var input;
var value = object.getAttribute("value");
switch(value){
case "flight":
input = "input1";
break;
case "hotel":
input = "input2";
break;
case "travel":
input = "input3";
break;
}
var elements = document.getElementsByClassName(input);
for(var i = 0; i < elements.length; i++){
if (elements[i].style.display == "block") {
elements[i].style.display = "none";
} else {
elements[i].style.display = "block";
}
}
document.getElementsByTagName("button")[0].style.display = "block";
}
.common {
margin-bottom: 8px;
}
input[type="text"]{
display:none;
}
button {
display:none;
}
<head>
<title></title>
</head>
<body>
<form id="main-form">
<input type="checkbox" onclick="toggle(this)" id="flight" value="flight"><label for="flight">Flight</label>
<input type="checkbox" onclick="toggle(this)" id="hotel" value="hotel"><label for="hotel">Hotel</label>
<input type="checkbox" onclick="toggle(this)" id="travel" value="travel"><label for="travel">Travel</label>
<br><br>
<input type="text" class="input1 common" placeholder="flight">
<input type="text" class="input1 common" placeholder="flight2">
<input type="text" class="input1 common" placeholder="flight3">
<input type="text" class="input2 common" placeholder="hotel">
<input type="text" class="input2 common" placeholder="hotel2">
<input type="text" class="input3 common" placeholder="travel">
<input type="text" class="input3 common" placeholder="travel2">
<input type="text" class="input3 common" placeholder="travel3">
<input type="text" class="input3 common" placeholder="travel4">
<button type="submit">Button</button>
</form>
<span id="show"></span>

Implementing Submit action in javascript

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

Categories

Resources