skip to Main Content

Ok, so I have this code here which is at the bottom of my question that prompts the user to enter a UserId, their first name, last name and birthday into the supplied input fields.

The most important part is that the code calculates the difference between the user’s birthday and today’s date in number of days. Then the number of days is printed to the page via the DOM like this:

let results2 = fname + " " + lname + ", " + "you have been breathing for " + daysDifference + " days!";
resultsDiv.innerHTML = results2;

The only problem is that when you click the accept button, the console logged variables are shown to be empty or undefined values and the DOM manipulated HTML outputs empty values as well. For whatever reason, you have to THEN refresh the page via F5 and click the accept button again in order for the console logged variables to output their correct values and for the DOM manipulated HTML to output the right stuff.


<!DOCTYPE html>
<html>
<body>

<div id="forms">

<form action="/action_page.php">

  <label for="user">User Id:</label>
  <input type="text" id="user" name="user" required><br>

  <label for="fname">First name:</label>
  <input type="text" id="firstname" name="fname" required><br>

  <label for="lname">Last name:</label>
  <input type="text" id="lastname" name="lname" required><br>

  <label for="birthday">Birthday:</label>
  <input type="date" id="birth" name="birthday" required><br>

  <input type="submit" id="submit-button" value="Accept">

</form>

</div>

<div>

<div id="results">



</div>

</div>

</div>

<script>

alert("Whenever you are ready; click the OK button and then please enter your first name, last name, a User ID and your birthdate (MM/DD/YYYY format) in their respective input fields on this website.");

let userid = document.getElementById("user").value;

function verifyUser() {

  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d).{8,12}$/;

  if (regex.test(userid)) {
    console.log("Valid UserId");
  } else {
    console.log("Invalid UserId");
  };

};

let fname = document.getElementById("firstname").value;

function verifyFirstName() {

  if (fname.trim() == "") {
    console.log("Invalid First Name");
  } else {
    console.log("Valid First Name");
  };

};

let lname = document.getElementById("lastname").value;

function verifyLastName() {

  if (lname.trim() == "") {
    console.log("Invalid Last Name");
  } else {
    console.log("Valid Last Name");
  };

};

today = new Date();
let birthDate = new Date(document.getElementById("birth").value);

let birthday = document.getElementById("birth").value;

function verifyBirthday() {

  if (birthday.trim() == "") {
    console.log("Invalid Birthday");
  } else {
    console.log("Valid Birthday");
  };

};

let daysDifference;

function daysDiff(birthDate) {

  let differenceMilliseconds = today.getTime() - birthDate.getTime();

   daysDifference = parseInt(differenceMilliseconds / (1000 * 60 * 60 * 24));

  return daysDifference;

};

const resultsDiv = document.getElementById("results");

function daysResults() {

  if (daysDifference < (365 * 18)) {
    let results1 = "You are probably not old enough to take this class!";
    resultsDiv.innerHTML = results1;
  } else {
    let results2 = fname + " " + lname + ", " + "you have been breathing for " + daysDifference + " days!";
    resultsDiv.innerHTML = results2;
  }

}

document.getElementById('submit-button').addEventListener('click', 
  function(event) {

    event.preventDefault();

    verifyUser();
    verifyFirstName();
    console.log(fname);
    verifyLastName();
    console.log(lname);
    verifyBirthday()
    daysDiff(birthDate);
    console.log(daysDifference);
    daysResults();

  }
);

let str = "";

for (let i = 0; i < 20; i++) {
  document.write(str.padStart(i,"x") + "<br>");
} 

</script>

</body>
</html>

I’m new to JS so I have no idea why this is happening. My assumption is that the inputted values are only set or updated whenever the accept button is clicked instead of it actively listening to the input fields being modified by the user.

2

Answers


  1. You need to fetch the field values every time you need to read them. This seems to do what you want:

    <!DOCTYPE html>
    <html>
    <body>
    
    <div id="forms">
    
    <form action="/action_page.php">
    
      <label for="user">User Id:</label>
      <input type="text" id="user" name="user" required><br>
    
      <label for="fname">First name:</label>
      <input type="text" id="firstname" name="fname" required><br>
    
      <label for="lname">Last name:</label>
      <input type="text" id="lastname" name="lname" required><br>
    
      <label for="birthday">Birthday:</label>
      <input type="date" id="birth" name="birthday" required><br>
    
      <input type="submit" id="submit-button" value="Accept">
    
    </form>
    
    </div>
    
    <div>
    
    <div id="results">
    
    </div>
    
    </div>
    
    </div>
    
    <script>
    
    let userid = '';
    
    function verifyUser() {
    
      userid = document.getElementById("user").value;
      const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*d).{8,12}$/;
    
      if (regex.test(userid)) {
        console.log("Valid UserId");
      } else {
        console.log("Invalid UserId");
      };
    
    };
    
    let fname = '';
    
    function verifyFirstName() {
    
      fname = document.getElementById("firstname").value;
      if (fname.trim() == "") {
        console.log("Invalid First Name");
      } else {
        console.log("Valid First Name");
      };
    
    };
    
    let lname = '';
    
    function verifyLastName() {
    
      lname = document.getElementById("lastname").value;
      if (lname.trim() == "") {
        console.log("Invalid Last Name");
      } else {
        console.log("Valid Last Name");
      };
    
    };
    
    let today = new Date();
    
    function verifyBirthday() {
    
      birthDate = new Date(document.getElementById("birth").value);
      birthday = document.getElementById("birth").value;
      if (birthday.trim() == "") {
        console.log("Invalid Birthday");
      } else {
        console.log("Valid Birthday");
      };
    
    };
    
    let daysDifference;
    
    function daysDiff(birthDate) {
    
      let differenceMilliseconds = today.getTime() - birthDate.getTime();
    
      daysDifference = parseInt(differenceMilliseconds / (1000 * 60 * 60 * 24));
    
      return daysDifference;
    
    };
    
    
    function daysResults() {
    
      let resultsDiv = document.getElementById("results");
      let result='';
      if (daysDifference < (365 * 18)) {
        result = "You are probably not old enough to take this class!";
      } else {
        result = fname + " " + lname + ", " + "you have been breathing for " + daysDifference + " days!";
      }
      resultsDiv.innerHTML = result;
    }
    
    document.getElementById('submit-button').addEventListener('click', 
      function(event) {
    
        event.preventDefault();
    
        verifyUser();
        verifyFirstName();
        console.log(fname);
        verifyLastName();
        console.log(lname);
        verifyBirthday()
        daysDiff(birthDate);
        console.log(daysDifference);
        daysResults();
      }
    );
    
    </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
  2. No needs of so much JS code…

    const
      myForm  = document.querySelector('#my-form');
    , one_day = 1000 * 60 * 60 * 24
    , toDay   = new Date()
      ;
    // set max date attribute
    myForm.birthday.max = new Date().toISOString().split("T")[0];
    
    myForm.addEventListener('submit', e =>
      {
      e.preventDefault();  // disable form submit just for testing
      
      myForm.daysCount.textContent = ( toDay.getTime() 
                                     - myForm.birthday.valueAsDate.getTime()
                                     ) / one_day;
      let data = Object.fromEntries(new FormData(myForm).entries());
     
      console.clear();
      console.log( JSON.stringify(data) );
      });
    body {
      font-family : Arial, Helvetica, sans-serif;
      font-size   : 16px;
      }
    fieldset {
      margin : 1rem;
      width  : 14rem;
      }
    legend {
      font-weight   : bold;
      font-size     : 1.4rem;
      margin-bottom : .2rem;
      }
    label {
      display    : block;
      margin-top : 0.8em;
      font-size  : .9rem;
      }
    input:not([type=checkbox]) {
      display    : block;
      }
    button {
      margin-top   : 1rem;
      margin-right : 1rem;
      width        : 40%;
      }
    <form action="/action_page.php" id="my-form">
      <fieldset>
        <legend> ? </legend>
        <label>
          User Id:
          <input  name="user" type="text" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*d).{8,12}$" required>
        </label>
        <label>
          First name:
          <input name="fname"  type="text" required>
        </label>
        <label>Last name:
          <input type="text" id="lastname" name="lname" required> 
        </label>
        <label>
          Birthday: 
          <input  name="birthday" type="date" max="" required>
        </label>
    
        <button type="submit"> Accept </button>
        <button type="reset" > Reset  </button>
    
        <output name="daysCount">_<output>
        </fieldset>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search