Q: Displaying error message and pre-filling a form On the 82 line of my JavaScript I have "document.getElementById("errors").innerHTML = errMsg;" this code and I was wondering how to implement it into my HTML page so when the validation isn't correct the error message will be displayed in the correct place such as when someone is younger then 15 the error message will be displayed next to date of birth. At the moment I have my errors appearing in an alert but I'd like them to appear on the web page. I also when to know if my "storeForm" and "prefillForm" functions are correct because I tried to test them and it doesn't seem to work. How do I go about fixing these?


"use strict";
/*get variables from form and check rules*/
function validate() {
  var errMsg = ""; /* stores the error message */
  var result = true; /* assumes no errors */
  //var JobID = document.getElementById("JobID").value;
  var firstName = document.getElementById("firstName").value;
  var familyName = document.getElementById("familyName").value;
  var midName = document.getElementById("midName").value;
  var male = document.getElementById("male").checked;
  var female = document.getElementById("female").checked;
  var street = document.getElementById("street").value;
  var suburb = document.getElementById("suburb").value;
  var state = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
  var postcode = document.getElementById("postcode").value;
  var email = document.getElementById("email").value;
  var number = document.getElementById("number").value;
  var XML = document.getElementById("XML").checked;
  var Java = document.getElementById("Java").checked;
  var Python = document.getElementById("Python").checked;
  var SQL = document.getElementById("SQL").checked;
  var PERL = document.getElementById("PERL").checked;
  var MySQL = document.getElementById("MySQL").checked;
  var Windows = document.getElementById("Windows").checked;
  var UNIX = document.getElementById("UNIX").checked;
  var Linux = document.getElementById("Linux").checked;
  var other = document.getElementById("other").checked;
  var otherText = document.getElementById("otherText").value;
  var dob = document.getElementById("dob").value.split("/");
  var date = new Date(dob[2], parseInt(dob[1]) - 1, dob[0]);
  var today = new Date();
  var age = today.getFullYear() - date.getFullYear();

  //get varibles from form and check rules here
  // if something is wrong set result = false, and concatenate error message

  if (age >= 80) { // Outside age ranges.
    errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
    result = false;
  }

  if (age <= 15) { // Outside age ranges.
    errMsg = errMsg + "You must be 15 or older to apply for this job\n";
    result = false;
  }

  if (!(postcode.charAt(0) == 3 || postcode.charAt(0) == 8) && state == "VIC") {
    errMsg = errMsg + "Your state and postcode do not match. State VIC postcodes must start with a 3 or 8\n";
    result = false;
  } else if (!(postcode.charAt(0) == 1 || postcode.charAt(0) == 2) && state == "NSW") {
    errMsg = errMsg + "Your state and postcode do not match. State NSW postcodes must start with a 1 or 2\n";
    result = false;
  } else if (!(postcode.charAt(0) == 4 || postcode.charAt(0) == 9) && state == "QLD") {
    errMsg = errMsg + "Your state and postcode do not match. State QLD postcodes must start with a 4 or 9\n";
    result = false;
  } else if (!(postcode.charAt(0) == 0) && state == "NT") {
    errMsg = errMsg + "Your state and postcode do not match. State NT postcodes must start with a 0\n";
    result = false;
  } else if (!(postcode.charAt(0) == 6) && state == "WA") {
    errMsg = errMsg + "Your state and postcode do not match. State WA postcodes must start with a 6\n";
    result = false;
  } else if (!(postcode.charAt(0) == 5) && state == "SA") {
    errMsg = errMsg + "Your state and postcode do not match. State SA postcodes must start with a 5\n";
    result = false;
  } else if (!(postcode.charAt(0) == 7) && state == "TAS") {
    errMsg = errMsg + "Your state and postcode do not match. State TAS postcodes must start with a 7\n";
    result = false;
  } else if (!(postcode.charAt(0) == 0) && state == "ACT") {
    errMsg = errMsg + "Your state and postcode do not match. State ACT postcodes must start with a 0\n";
    result = false;
  } else {
    result = true;
  }

  if (other && document.getElementById("otherText").value.trim().length === 0) {
    errMsg = errMsg + "You have selected other skills, you must enter one other skill in the text box\n";
    result = false;
  }

  if (errMsg != "") { //only display message box if there is something to show
    alert(errMsg);
    //document.getElementById("errors").innerHTML = errMsg;
  }

  if (result == true) {
    storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText)
  }
  return result; //if false the information will not be sent to the server
}

function storeForm(firstName, familyName, midName, dob, male, female, street, suburb, state, postcode, email, number, XML, Java, Python, SQL, PERL, MySQL, Windows, UNIX, Linux, other, otherText) {
  //get values and assign them to sessionStorage attribute.
  //we use the same name for the attrubute and the element id to avoid confustion
  sessionStorage.firstName = firstName;
  sessionStorage.familyName = familyName;
  sessionStorage.midName = midName;
  sessionStorage.dob = dob;
  sessionStorage.male = male;
  sessionStorage.female = female;
  sessionStorage.street = street;
  sessionStorage.suburb = suburb;
  sessionStorage.state = state;
  sessionStorage.postcode = postcode;
  sessionStorage.email = email;
  sessionStorage.number = number;
  sessionStorage.XML = XML;
  sessionStorage.Java = Java;
  sessionStorage.Python = Python;
  sessionStorage.SQL = SQL;
  sessionStorage.PERL = PERL;
  sessionStorage.MySQL = MySQL;
  sessionStorage.Windows = Windows;
  sessionStorage.UNIX = UNIX;
  sessionStorage.Linux = Linux;
  sessionStorage.other = other;
  sessionStorage.otherText = otherText;
}

/* check if session day on user exists and if so prefill the form*/
function prefillForm() {
  if (sessionStorage.firstName != undefined) {
    document.getElementById("firstName").value = sessionStorage.firstName;
    document.getElementById("familyName").value = sessionStorage.familyName;
    document.getElementById("midName").value = sessionStorage.midName;
    document.getElementById("dob").value = sessionStorage.dob;
    if (sessionStorage.male == ("true")) {
      document.getElementById("male").checked = true;
    }
    if (sessionStorage.female == ("true")) {
      document.getElementById("female").checked = true;
    }
    document.getElementById("street").value = sessionStorage.street;
    document.getElementById("suburb").value = sessionStorage.suburb;
    document.getElementById("state").value = sessionStorage.state;
    document.getElementById("postcode").value = sessionStorage.postcode;
    document.getElementById("email").value = sessionStorage.email;
    document.getElementById("number").value = sessionStorage.number;
    if (sessionStorage.XML == ("true")) {
      document.getElementById("XML").checked = true;
    }
    if (sessionStorage.Java == ("true")) {
      document.getElementById("Java").checked = true;
    }
    if (sessionStorage.Python == ("true")) {
      document.getElementById("Python").checked = true;
    }
    if (sessionStorage.SQL == ("true")) {
      document.getElementById("SQL").checked = true;
    }
    if (sessionStorage.PERL == ("true")) {
      document.getElementById("PERL").checked = true;
    }
    if (sessionStorage.MySQL == ("true")) {
      document.getElementById("MySQL").checked = true;
    }
    if (sessionStorage.Windows == ("true")) {
      document.getElementById("Windows").checked = true;
    }
    if (sessionStorage.UNIX == ("true")) {
      document.getElementById("UNIX").checked = true;
    }
    if (sessionStorage.Linux == ("true")) {
      document.getElementById("Linux").checked = true;
    }
    if (sessionStorage.other == ("true")) {
      document.getElementById("other").checked = sessionStorage.other;
    }
    document.getElementById("otherText").value = sessionStorage.otherText;
  }
}

function referenceNum1() {
  //this function defines the local storage for the first job
  localStorage.JobID = "QM593";
}

function referenceNum2() {
  //this function defines the local storage for the second job;
  localStorage.JobID = "CS197";
}

function init() {
  var path = window.location.pathname;
  var page = path.split("/").pop();

  if (page == "apply.html") {
    var regForm = document.getElementById("regform"); // get ref to the HTML element
    window.onload = prefillForm();
    regForm.onsubmit = validate; //register the event listener 
    //this puts the job id into the field
    document.getElementById("JobID").value = localStorage.JobID;
  } else {
    //this makes it so that the 2 different functions run when the hyperlinks are clicked
    var job1 = document.getElementById("job1");
    var job2 = document.getElementById("job2");
    var JobID
    job1.onclick = referenceNum1;
    job2.onclick = referenceNum2;
  }
}

window.onload = init;
<article>
  <header>
    <h1>The Virtual World</h1>

    <nav>
      <p class="menu"><a href="index.html#home">Home</a></p>
      <p class="menu"><a href="jobs.html#jobs">Jobs</a></p>
      <p class="menu"><a href="apply.html#apply">Apply</a></p>
      <p class="menu"><a href="about.html#about">About</a></p>
      <p class="menu"><a href="enhancements.html#enhancements">Enhancements</a></p>
    </nav>
  </header>
  <section id="required">
    <h5>All fields with * are required</h5>
  </section>
  <form id="regform" method="post" action="http://mercury.swin.edu.au/it000000/formtest.php">
    <fieldset>
      <legend>Job Application</legend>
      <p><label for="JobID">*Job ID:</label>
        <input type="text" name="JobID" id="JobID" maxlength="5" size="10" pattern="^[a-zA-Z]{2}[0-9]{3}$" required="required" /></p>
      <section id="choose">
        <h5>Please choose from QM593 or CS197</h5>
      </section>
      <fieldset>
        <legend>Personal Details</legend>
        <p><label for="title">*Title:</label>
          <select name="title" id="title" required="required">
            <option value="">Please Select</option>         
            <option value="title">Dr</option>
            <option value="title">Mr</option>
            <option value="title">Miss</option>
            <option value="title">Mrs</option>
            <option value="title">Ms</option>
         </select></p>
        <p><label for="firstName">*First Name:</label>
          <input type="text" name="firstName" id="firstName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" />

          <label for="familyName">*Family Name:</label>
          <input type="text" name="familyName" id="familyName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" required="required" /></p>

        <p><label for="midName">Middle Name:</label>
          <input type="text" name="midName" id="midName" maxlength="20" size="20" pattern="^[a-zA-Z ]+$" /></p>

        <p><label for="dob">*Date of Birth:</label>
          <input type="text" name="dob" id="dob" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" maxlength="10" size="10" required="required" /></p>

        <p>*Gender:
          <label for="male">Male</label>
          <input type="radio" id="male" name="sex" value="male" required="required" />
          <label for="female">Female</label>
          <input type="radio" id="female" name="sex" value="female" required="required" /></p>

        <p><label for="street">*Street Address:</label>
          <input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>

        <p><label for="suburb">*Suburb/town:</label>
          <input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>

        <p><label for="state">*State:</label>
          <select name="state" id="state" required="required">
            <option value="">Please Select</option>         
            <option value="state">VIC</option>
            <option value="state">NSW</option>
            <option value="state">QLD</option>
            <option value="state">NT</option>
            <option value="state">WA</option>
            <option value="state">SA</option>
            <option value="state">TAS</option>
            <option value="state">ACT</option>
         </select></p>

        <p><label for="postcode">*Postcode:</label>
          <input type="text" name="postcode" id="postcode" minlength="4" maxlength="4" size="10" pattern="^[0-9]{4}$" required="required" /></p>

        <p><label for="email">*Email:</label>
          <input type="email" name="email" id="email" size="30" required="required" /></p>

        <p><label for="number">*Phone number:</label>
          <input type="tel" name="number" id="number" minlength="8" maxlength="12" size="10" required="required" /></p>

        <p>Skill list:</p>
        <p><label for="C/C+">C/C+</label>
          <input type="checkbox" id="C/C+" name="category[]" checked="checked" /></p>
        <p><label for="XML">XML</label>
          <input type="checkbox" id="XML" name="category[]" /></p>
        <p><label for="Java">Java</label>
          <input type="checkbox" id="Java" name="category[]" /></p>
        <p><label for="Python">Python</label>
          <input type="checkbox" id="Python" name="category[]" /></p>
        <p><label for="SQL">SQL</label>
          <input type="checkbox" id="SQL" name="category[]" /></p>
        <p><label for="PERL">PERL</label>
          <input type="checkbox" id="PERL" name="category[]" /></p>
        <p><label for="MySQL">MySQL</label>
          <input type="checkbox" id="MySQL" name="category[]" /></p>
        <p><label for="Windows">Windows</label>
          <input type="checkbox" id="Windows" name="category[]" /></p>
        <p><label for="UNIX">UNIX</label>
          <input type="checkbox" id="UNIX" name="category[]" /></p>
        <p><label for="Linux">Linux</label>
          <input type="checkbox" id="Linux" name="category[]" /></p>
        <p><label for="other">Other Skills:</label>
          <input type="checkbox" id="other" name="category[]" /></p>
        <textarea id="otherText" name="other" rows="8" cols="70" placeholder="Please write any other skills you may have here..."></textarea>
        </p>
      </fieldset>
    </fieldset>
    <input type="submit" value="Apply" />
    <input type="reset" value="Reset Application" />
  </form>
</article>



A: You can do the below to update when there is an error. I have added a small code to demonstrate.


$(document).ready(function() {
  $("#btn").click(function() {
    validate();
  });
});

function validate() {
  var errMsg = "";
  var date = new Date($('#dpDoB').val());
  var today = new Date();
  var age = today.getFullYear() - date.getFullYear();


  if (age >= 80) { // Outside age ranges.
    errMsg = errMsg + "You must be 80 or younger to apply for this job\n";
    $("#dob").append("<span>" + errMsg + "</span>");
    result = false;
  }

  if (age <= 15) { // Outside age ranges.
    errMsg = errMsg + "You must be 15 or older to apply for this job\n";
    $("#dob").append("<span>" + errMsg + "</span>");
    result = false;
  }
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<div id="form">
  <div id="dob">
    <input id="dpDoB" type="date" />
  </div>
  <div>
    <input type="button" id="btn" class="btn btn-default" value="click me">
  </div>

</div>



A: you may create a generic function like that :


function show_error(element, message) {
  element.parentElement.innerHTML += "<span class='error'>" + message + "</span>";
}
//call the function
show_error(document.getElementById('street'), 'error message');
.error {
  color: red;
}
<p><label for="street">*Street Address:</label>
  <input type="text" name="street" id="street" maxlength="40" size="30" required="required" /></p>

<p><label for="suburb">*Suburb/town:</label>
  <input type="text" name="suburb" id="suburb" maxlength="40" size="20" required="required" /></p>


Then you can add another function to remove this error.
