How do I use javascript to create two button popups where the user can type in their name?

Viewed 38

My sticking point is how to create two buttons and identify them separately within JS?

What the lecturer asks for in the image to create two buttons and two click functions.

My HTML code with the script tags:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
    
<title>Popup Boxes Lesson</title>

<body>  
<button onclick="Enter Name">Click here for a popup alert</button>

</body>

<script>
function myFunction() { 
        alert("Enter your Name");
        
        }
function myFunction(){
        alert("Generate Greeting");
        }
        
</script>

</html>
2 Answers

First of all create two different functions with different names. Then you can use them with onclick OR Give them id and then use document.getElementById("id") to assign the click event on it. Something like this

<body> 
<button id="foo">Click here for a popup alert</button>
</body>
    <script>
    document.getElementById('foo').onclick = function(){
        prompt('Hello world');
    }
</script>

There are several problems with your code:

First the click event you assigned to the button does not match the function you created. Second don't create two functions with same names

The code should look like this:

<!DOCTYPE html>
<html>
<head>
<title>
Example
</title>
</head>
<body>
<button onclick="myFunction()">
Enter your name
</button>
<button onclick="generateMessage()">
Generate Message
</button>
<script>
function myFunction(){
var message = prompt("What is your name?");
}
function generateMessage(){
alert("Hello " + message);
}
</script>
</body>
</html>
Related