1

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.

Mamun
  • 58,653
  • 9
  • 33
  • 46
Alapan Bag
  • 225
  • 2
  • 3
  • 13

3 Answers3

4

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>
Mamun
  • 58,653
  • 9
  • 33
  • 46
1

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>
Mihai Alexandru-Ionut
  • 41,021
  • 10
  • 77
  • 103
0

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>