I want to make 2 buttons appear onclick. How can I do this with Javascript? The code is supposed to ask a user "How their doing?" and then give them 2 options to choose from.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function helloName() {
// GET THE USERS INPUT
var userName = document.getElementById("name").value;
// GREET USER WITH THEIR NAME
document.write("Hello " + userName + ", How are you doing today?");
// GIVE USER AN OPTION TO SELECT HOW THEIR FEELING
document.getElementById("show-buttons").style.display = 'block';
};
</script>
</head>
<body>
<h1>JS Skills Test</h1>
<label for="name">Enter Your Name</label>
<input id="name" type="text" placeholder="Enter Your Name">
<button onclick="helloName()">Click Me</button>
<div id="show-buttons" style="display: none;">
<button id="bad">I'm not doing to well</button>
<button id="good">I'm doing wonderful</button>
</div>
</body>
</html>
When you do document.write()
, all the dom element will be deleted, try this:
function helloName() { // GET THE USERS INPUT var userName = document.getElementById("name").value; // GREET USER WITH THEIR NAME document.getElementById("message").innerText = "Hello " + userName + ", How are you doing today?"; // GIVE USER AN OPTION TO SELECT HOW THEIR FEELING document.getElementById("show-buttons").style.display = 'block'; };
<h1>JS Skills Test</h1> <label for="name">Enter Your Name</label> <input id="name" type="text" placeholder="Enter Your Name"> <button onclick="helloName()">Click Me</button> <div id="message"></div> <div id="show-buttons" style="display: none;"> <button id="bad">I'm not doing to well</button> <button id="good">I'm doing wonderful</button> </div>
You add an event listener on click on the div and add or change css class which contains visibility or display properties.
function helloName() {
const x =
document.getElementById("show-buttons");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
You could also use style visibility: visible; or visibility: hidden;
This can be found simple on w3schools.com btw.
You could do something like:
function helloName() {
document.getElementById('message').innerText = "Hello"+ userName + ", How are you doing today?";
var x = document.getElementById("show-buttons");
x.style.display="block";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.