0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Matt
  • 3
  • 2
  • try preventing default action, page is reloading because that's what happens when you submit the form. in your case you need to prevent that default action. try this https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission – Gulam Hussain Oct 24 '19 at 06:54

2 Answers2

1

In your validForm function you are trying to access a form (myForm) as well as a input field (numberOfDays) both of them doesn't exist in your html code, it will throw an error.

instead of

var x = document.forms["myForm"]["numberOfDays"].value;

use

var form = document.forms["thisForm"]; //will return form

and in HTML code, give a unique name to each input field to access it using form object.

I have given each input field a name , so that you can access its value using its name, for example to access first name, use form.fName.value.

I have updated your html code as well as your validation function

function validForm() {
    var form = document.forms["thisForm"]
    var fName = form.fName.value;
    var lName = form.lName.value;
    var age =form.age.value;
    var email = form.email.value;
    if (fName == "") {
        alert("First name must be filled out");
        return false;
    }
    if (lName == "") {
        alert("Last name must be filled out");
        return false;
    }
    if (age == "") {
        alert("age must be filled out");
        return false;
    }
    if (email == "") {
        alert("email must be filled out");
        return false;
    };
    
    //call your next function here
    //loopForm(form);
}
<form id="thisForm" method="post" name="thisForm" onsubmit="return validForm()">
      <label>First name:</label>
      <input name="fName" autocomplete="on" id="firstNameInput" placeholder="John"  title="Enter your first name" type="text"><br>

      <label>Last name:</label>
      <input name="lName" autocomplete="on" id="lastNameInput" placeholder="Smith" title="Enter your last name" type="text"><br>

      <label>Age:</label>
      <input name="age" autocomplete="on" id="ageInput" placeholder="18"  title="Enter your age" type="number"><br>

      <label>Email address:</label>
      <input name="email" autocomplete="on" id="emailInput" placeholder="johnsmith@gmail.com"  title="Enter your email address" type="email">

      <button class="button button1" id="submit" >Confirm Booking</button>

      <button class="button button2" id="reset" onclick="index.html">Reset</button>
</form>
Gulam Hussain
  • 1,591
  • 10
  • 19
  • 1
    @halfer i have updated my answer, thanks for your suggestion to add more explanation. – Gulam Hussain Oct 29 '19 at 04:23
  • 1
    Great, thank you. Answers are best if you can write them generally enough for the future reader, with assistance given to the question author as an extra bonus. Your answer now will be much more helpful for others reading this page `:-)`. – halfer Oct 29 '19 at 08:49
0

You can make single function to perform your action move your validform code into the loopform function. If form is not valid return false something like below function.

function loopForm(form) { 
    var x = document.forms["myForm"]["numberOfDays"].value;
    if (x == "") 
     {
       alert("Name must be filled out");
        return false;
     }
    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);

                outputDays.innerHTML = amountOfDays; 
                outputTest.innerHTML = insuranceCost; 
                outputVehicle.innerHTML = vehicleResult; 
            }
        }
        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;
            }
        }
    }

return true;
}