I want to call a Javascript function when the user clicks a button, but the function is inside a condition. Here is the HTML:
<button id="demo" onclick="myFunction">Hello</button>
And here is the Javascript function:
var x = document.getElementById("demo"); if (x == "Hello") function myFunction { document.getElementById("demo").innerHTML = "Good morning"; }
When I click on the button nothing happens. If I delete the if statement, the function work, but I want it to be into a condition. Can you help me in solving this stupid problem?
You'll need to change your function to something like this
function myFunction (){
var x = document.getElementById("demo");
if (x.innerHTML == "Hello"){
document.getElementById("demo").innerHTML = "Good morning";
}
}
There are 2 issues here:
<button id="demo" onclick="myFunction()">Hello</button>
function myFunction() {
var x = document.getElementById("demo").innerHTML;
if (x == "Hello"){
document.getElementById("demo").innerHTML = "Good morning";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.