Alapan Bag
Alapan Bag

Reputation: 265

How to return the system date by clicking a button using a JavaScript function?

I wanted to show the system date after clicking the button, but after clicking the button it shows nothing. I have just started JavaScript and I don't know what I am doing wrong.

function dateFunc() {
   return this.innerHTML = Date();
}
<button onclick="dateFunc()">The time is?</button>

Thanks in advance.

Upvotes: 1

Views: 1694

Answers (3)

Mamun
Mamun

Reputation: 68933

You have to pass this to the function so that you can refer that inside the function:

function dateFunc(thatBtn) {
   return thatBtn.innerHTML = Date();
}
<button onclick="dateFunc(this)">The time is?</button>

Upvotes: 4

JackGoldfinch
JackGoldfinch

Reputation: 76

Within dateFunc(), this is the window, which has no attribute innerHTML.

You could define an additional element to display the time and get that in dateFunc() via documnet.getElementById():

<!DOCTYPE html>
<html>
    <body>

    <button onclick="dateFunc()">The time is?</button>
    <div id="display"></div>

    <script>
        function dateFunc() {
            document.getElementById("display").innerHTML=Date();
        }
    </script>

    </body>
</html>

Upvotes: 0

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48417

The issue is in this line:

return this.innerHTML=Date();

because this is just a reference which points to window object.

Use DOM manipulation instead.

function dateFunc() {
   return document.getElementById('result').innerHTML=Date();
}
<button onclick="dateFunc()">The time is?</button>
<div id="result"></div>

Upvotes: 1

Related Questions