Reputation: 265
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
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
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
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