I'm doing a practice task for my digital class and I am stuck with my booking form. I have two functions that should run on the click of a button, one validates the form checking if everything is filled out and the other runs the main loop. I have been scanning this website for similar situations but I just can't work it out.
I have tried adding the validForm function to my main loop so it ran that first and then the main loop. I then tried running the main loop itself without the validForm function but it ran the main loop THEN checked for required forms (I need it to check for required forms then run the loop). I just can't work it out.
--- shortened form (html) ---
<form id="thisForm" method="post" name="thisForm" onsubmit="validForm()">
<label>First name:</label> <input autocomplete="on" id="firstNameInput" placeholder="John" required="" title="Enter your first name" type="text"><br>
<label>Last name:</label> <input autocomplete="on" id="lastNameInput" placeholder="Smith" required="" title="Enter your last name" type="text"><br>
<label>Age:</label> <input autocomplete="on" id="ageInput" placeholder="18" required="" title="Enter your age" type="number"><br>
<label>Email address:</label> <input autocomplete="on" id="emailInput" placeholder="johnsmith@gmail.com" required="" title="Enter your email address" type="email">
<button class="button button1" id="submit" onsubmit="loopForm(form)">Confirm Booking</button>
<button class="button button2" id="reset" onclick="index.html">Reset</button>
</form>
--- shortened javascript ---
function validForm() {
var x = document.forms["myForm"]["numberOfDays"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
function loopForm(form) { //this function is called once the confirm button is clicked, sends data to firebase
alert('Test alert for confirm booking');
var amountOfDays = numberOfDays.value;
var insuranceFee = 20;
var BOOKINGFEE = 50;
var sum = 0 ;
var cbResults = ' ';
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].type == 'radio') {
if (form.elements[i].checked == true) {
vehicleResult = form.elements[i].value;
vehicleCost = form.elements[i].dataset.price;
insuranceCost = Math.round(insuranceFee + vehicleCost * amountOfDays);
//ouputs
outputDays.innerHTML = amountOfDays; //working
outputTest.innerHTML = insuranceCost; //wrong but working
outputVehicle.innerHTML = vehicleResult; //working
}
}
if (form.elements[i].type == "checkbox") {
if (form.elements[i].checked == true) {
cbResults += form.elements[i].value + ', ';
sum = sum + parseInt(form.elements[i].dataset.price);
alert(cbResults + "$" + sum);
outputExtras.innerHTML = cbResults;
totalCost = Math.round(insuranceCost + sum + BOOKINGFEE); //devired values
outputCost.innerHTML = '$' + totalCost;
}
}
}
}
I expect the output to go to a booking summary instead, the page checks for required fields then the page refreshes before I get to see the booking summary.