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
  • 66,969
  • 9
  • 47
  • 59
Alapan Bag
  • 255
  • 2
  • 3
  • 15

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
  • 66,969
  • 9
  • 47
  • 59
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
  • 47,092
  • 13
  • 101
  • 128
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>