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>
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
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP