I'm working on a project for one of my classes and it requires me to have two alert boxes pop up to ask for age and name. I have two buttons on my page to initiate the functions to bring up those two alert boxes. The first button works fine but the second one does not for whatever reason.
function askAge() {
let text;
let age = prompt("Please enter your age:", "");
if (age == null || age == "") {
text = "User exited prompt :( ";
} else {
text = "Your age is: " + age;
}
document.getElementById("age").innerHTML = text;
}
function askName() {
let text;
let person = prompt("Please enter your name:", "");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("name").innerHTML = text;
}
<!doctype html>
<html lang="en">
<link rel="javascript" href="js/java.js">
<link rel="stylesheet" href="css/style.css">
<title> Happy Birthday </title>
<head>
<p id="name"></p>
<p id="age"></p>
<button type="button" onclick="askName();">Click Me for name</button>
<button type="button" onclick="askAge();">Click Me for age</button>
</head>
</html>
Any ideas on where I'm being an idiot? I'm not even sure if you can have two alert boxes on a page. Anything will help.
You have missed a closing "}" for you askAge function (needs one right before the closing script tag), hence the second popup is missing.
While fixing that just want to point out that the variable names in the askAge function is off (probably a copy/paste error.)
you're querying for an element with the Id of 'age' when you element has the Id of askAge
Here's your fix with some important bits added too.
<!doctype html>
<html lang="en">
<head>
<link rel="javascript" href="js/java.js">
<link rel="stylesheet" href="css/style.css">
<title> Happy Birthday </title>
</head>
<body>
<p id="name"></p>
<button type="button" onclick="askName();">Click Me for name</button>
<button type="button2" onclick="askAge();">Click Me for age</button>
<p id="askAge"></p>
<script language="javascript">
function askName()
{
let text;
let person=prompt('Please enter your name:','');
if(person==null||person=='')
{
text='User cancelled the prompt.';
}
else
{
text='Hello '+person+'! How are you today?';
}
document.getElementById('name').innerHTML=text;
}
function askAge()
{
let text;
let person=prompt('Please enter your age:','');
if(person==null||person=='')
{
text='User exited prompt :(';
}
else
{
text='Your age is: '+age;
}
document.getElementById('age').innerHTML=text;
}
</script>
</body>
</html>
The thing breaking your version is a missing curly bracket at the end of the askAge function.