Linking 2 unctions to one button

Hi , I was trying to link 2 functions to one button. One function adds my name to the p tag and the second function displays an alert message. I am abel to run both of these successfully on 2 different buttons but I want to execute both the functions from a single button. The below code executes only the show_name() function.

	<title>Java Webpage </title>
	<h1> Java script</h1>
	<h3> Click on the box below to show the name</h3>
  	<button onclick="show_name('dhruva');"  , onclick="sayhello();">SHOW MY NAME</button>
    <p id="demo" style="color: red">YOUR NAME IS </p>
		<script type="text/javascript" src = "my-java-script.js"></script>

var x=6 ;
var y=3;
var m = x*y
var Multiplication = "Multiplication of " + x + " " + “and " + y +” "+ "is " + m
//document.getElementById(“demo”).innerHTML = Multiplication ; //accessing the hmtl element

function show_name(my_name){
	var predif = document.getElementById("demo"); 
	predif.innerHTML = predif.innerHTML + my_name; 
function sayhello(){
	setTimeout(function(){alert("Your name is displayed");}, 3000)

How do I solve it and make a program in which on clicking the button, the name is also added and after 3 seconds, the alert also comes.

Hi @jindaldhruva in your JS file you’re missing semicolons after statements .
And some inverted commas have mismatch which throws an error.The correct statement for the var multiplication line will be

var Multiplication = "Multiplication of " + x + " " + “and " + y +” "+ "is " + m ;

And for the single button functionality you can put the second function right after the first function’s semicolon as shown below.

<button onclick="show_name('dhruva');sayhello();">SHOW MY NAME</button>

Also i’d suggest you put that script tag in the Preformatted text of your code , to keep the code clean and easier to interpret.

1 Like
function sayhello(){
	setTimeout(function(){alert("Your name is displayed");}, 3000)

Try putting a semicolon after setTimeout(); function

1 Like

Thanks @akhil , your solution really helps me. Also, just to let you know, I purposely added those blank inverted commas to make spaces between the characters otherwise on the webpage, they were right beside each other.

1 Like