skip to Main Content

I’m making a small program that calculates your birth year to try and apply what I’ve learned, but when I change the style of a div container to ‘block’ using JavaScript, it appears then disappears extremely quickly.

Expected: The div box appears after the ‘submit’ button is pressed and the calculations are done.

Result: The div box appears then disappears extremely quick.

Form that collects data to calculate birth year:

let currentYear = new Date().getFullYear();
let age = null;
let birthYear = null;
let hadBirthDay = null;

let answerBox = document.getElementById("answerBox");

answerBox.style.display = "none";

function returnAge() {
  age = document.getElementById("age").value;
  //finds value of the radio input
  document.getElementsByName("bday").forEach((radio) => {
    if (radio.checked) {
      hadBirthDay = radio.value;
    }
  });
  if (age && hadBirthDay) {
    calculateBirthYear();
  }
}

function calculateBirthYear() {
  // calculates birth year
  if (hadBirthDay === "yes") {
    birthYear = currentYear - age;
  } else if (hadBirthDay === "no") {
    birthYear = currentYear - age - 1;
  }
}

function revealAnswer() {
  answerBox.style.display = "block";
}
#answerBox {
  background-color: #2d415e;
  color: #7194c9;
  padding: 5px;
  margin-top: 20px;
  margin-left: 150px;
  margin-right: 150px;
  height: auto;
  text-align: center;
  border-radius: 50px;
}
<form>
  <section>
    <label for="age">Insert Age:</label>
    <input type="number" min="0" id="age" name="age" required />
  </section>

  <br />

  <section class="bday">
    <span>Have you had your birthday this year?</span>
    <br />
    <input type="radio" id="yes" name="bday" value="yes" class="radio" required />
    <label for="yes">Yes</label>
    <input type="radio" id="no" name="bday" value="no" class="radio" required />
    <label for="no">No</label>
  </section>

  <br />

  <button id="submit" onclick="returnAge()">Submit</button>
</form>

<!-- html of the div that isn't working : -->
<section>
  <h2 id="answerBoxText" class="answer">YOU WERE BORN IN:</h2>
  <div id="answerBox" class="answer">
    <h3 id="answerText" class="answer">year</h3>
  </div>
</section>

2

Answers


  1. Your code is missing two things, a call to revealAnswer() and actually putting the answer into the answerBox div.

    I added the revealAnswer() call right after your calculateBirthYear() call and modified calculateBirthYear() to add the answer to the DOM.

    EDIT: As @Daniels118 pointed out, I also added a call to event.preventDefault in the returnAge() event handler. Without that, the form will be submitted and the html page be replaced with the response.

    let currentYear = new Date().getFullYear();
    let age = null;
    let birthYear = null;
    let hadBirthDay = null;
    
    let answerBox = document.getElementById("answerBox");
    
    answerBox.style.display = "none";
    
    function returnAge(event) {
      event.preventDefault()
      
      age = document.getElementById("age").value;
      //finds value of the radio input
      document.getElementsByName("bday").forEach((radio) => {
        if (radio.checked) {
          hadBirthDay = radio.value;
        }
      });
      if (age && hadBirthDay) {
        calculateBirthYear();
    
        revealAnswer();
      }
    }
    
    function calculateBirthYear() {
      // calculates birth year
      if (hadBirthDay === "yes") {
        birthYear = currentYear - age;
      } else if (hadBirthDay === "no") {
        birthYear = currentYear - age - 1;
      }
    }
    
    function revealAnswer() {
      document.querySelector("#answerBox").innerText = birthYear;
    
      answerBox.style.display = "block";
    }
    #answerBox {
      background-color: #2d415e;
      color: #7194c9;
      padding: 5px;
      margin-top: 0px;
      margin-left: 150px;
      margin-right: 150px;
      height: auto;
      text-align: center;
      border-radius: 50px;
    }
    
    h2 {
      margin: 4px;
    }
    <form>
      <section>
        <label for="age">Insert Age:</label>
        <input type="number" min="0" id="age" name="age" required />
      </section>
    
      <br />
    
      <section class="bday">
        <span>Have you had your birthday this year?</span>
        <br />
        <input type="radio" id="yes" name="bday" value="yes" class="radio" required />
        <label for="yes">Yes</label>
        <input type="radio" id="no" name="bday" value="no" class="radio" required />
        <label for="no">No</label>
      </section>
    
      <br />
    
      <button id="submit" onclick="returnAge(event)">Submit</button>
    </form>
    
    <!-- html of the div that isn't working : -->
    <section>
      <h2 id="answerBoxText" class="answer">YOU WERE BORN IN:</h2>
      <div id="answerBox" class="answer">
        <h3 id="answerText" class="answer">year</h3>
      </div>
    </section>
    Login or Signup to reply.
  2. The issue is that the page reloads as soon as you click the button. When clicking the button (with either no type defined or type defined as submit) in a form two event happen: The click event and the submit event. You are mixing them. Just listen for the submit event in this case and make sure that you call e.preventDefault() to stop the form from submitting and thereby reloading the page.

    In general, don’t use IDs that often (they must be unique) and not have too many global variables. As an example I moved the let age = null; into the callback function of the submit event instead of having it defined as a global variable. Let’s say that another function gave age the wrong value — it is mush more predictable to define the variable when you are going to use it.

    let form = document.forms.form01;
    let answerBox = form.querySelector(".answerBox");
    
    answerBox.style.display = "none";
    
    form.addEventListener('submit', e => {
      e.preventDefault();
      let form = e.target;
      let age = form.age.valueAsNumber;
      
      // calculates birth year
      let currentYear = new Date().getFullYear();
      let birthYear = currentYear - age;
      if(form.bday.value == 'no') birthYear--;
      
      // show answer
      form.output.value = birthYear;
      answerBox.style.display = "block";
    });
    .answerBox {
      background-color: #2d415e;
      color: #7194c9;
      padding: 5px;
      margin-top: 0px;
      margin-left: 150px;
      margin-right: 150px;
      height: auto;
      text-align: center;
      border-radius: 50px;
    }
    
    h2 {
      margin: 4px;
    }
    <form name="form01">
      <section>
        <label>Insert Age: <input type="number" min="0" name="age" required></label>
      </section>
    
      <section class="bday">
        <div>Have you had your birthday this year?</div>
        <label><input type="radio" name="bday" value="yes" class="radio" required> Yes</label>
        <label><input type="radio" name="bday" value="no" class="radio"> No</label>
      </section>
      <button type="submit">Submit</button>
      <section>
        <h2>YOU WERE BORN IN:</h2>
        <div class="answerBox">
          <h3 id="answerText"><output name="output"></output></h3>
        </div>
      </section>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search