TransWikia.com

My "else" statement does not work. It keeps showing the "if" statement's alert even if it's below 14

Stack Overflow Asked by user14391700 on February 15, 2021

  function buy() {

    let name = prompt("What is your name?");

    let age = prompt("How old are you?");

    if (age <= 14) {

        alert("Hey, " + name + "! ? Have fun buying on our site! ?");

    } else {

          alert("Sorry, " + name + "...? You are too young to buy on our website. You might have to ask your parents. ?");

    }

  }

  let buyButton = document.querySelector(".buy-button");

  buyButton.addEventListener("click", buy);
<button class="buy-button">Buy Button</button>

2 Answers

The value you get from prompt is string so it is needed to parse the string age value into number page value for comparison.

function buy() {
  let name = prompt("What is your name?");
  let age = prompt("How old are you?");
  
  age = parseInt(age); // This is the part you should add.
  if (age <= 14) {
    alert("Hey, " + name + "! ? Have fun buying on our site! ?");
  } else {
    alert("Sorry, " + name + "...? You are too young to buy on our website. You might have to ask your parents. ?");
  }
}

let buyButton = document.querySelector(".buy-button");
buyButton.addEventListener("click", buy);
<button class="buy-button">Buy Button</button>

Answered by Derek Wang on February 15, 2021

Your expression in the if statement is backwards. It should be age >= 14

function buy() {

  let name = prompt("What is your name?");

  let age = prompt("How old are you?");

  if (age >= 14) {

    alert("Hey, " + name + "! ? Have fun buying on our site! ?");

  } else {

    alert("Sorry, " + name + "...? You are too young to buy on our website. You might have to ask your parents. ?");

  }

}

let buyButton = document.querySelector(".buy-button");

buyButton.addEventListener("click", buy);
<button class="buy-button">Buy</button>

Answered by symlink on February 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP