Here’s my HTML:
JavaScript
x
20
20
1
<!doctype html>
2
3
<html lang="en">
4
<head>
5
<meta charset="utf-8">
6
7
<title>BookInc</title>
8
<link rel="stylesheet" href="style.css">
9
10
</head>
11
12
<body style="background-color:white;">
13
14
<div id= "mainPage">
15
16
</div>
17
<script src="test.js"></script>
18
</body>
19
</html>
20
and my javascript:
JavaScript
1
7
1
var btn = document.createElement('input');
2
btn.type = "button";
3
btn.className = "btn";
4
btn.value = "Negociate";
5
btn.onclick = console.log("hello");
6
document.getElementById('mainPage').appendChild(btn);
7
When my button is created the onclick event is fired automatically (I get hello printed in the console without clicking on the button) and then doesn’t work. When I inspected the page I realized that my button didn’t have an onclick anymore (just class and value)
I can’t figure out why so any help would be greatly appreciated. Thanks.
Advertisement
Answer
onclick
needs to be a function. Please see the example.
JavaScript
1
10
10
1
var sayHello = function(){
2
console.log("hello");
3
};
4
5
var btn = document.createElement('input');
6
btn.type = "button";
7
btn.className = "btn";
8
btn.value = "Negociate";
9
btn.onclick = sayHello;
10
document.getElementById('mainPage').appendChild(btn);
JavaScript
1
19
19
1
<!doctype html>
2
3
<html lang="en">
4
<head>
5
<meta charset="utf-8">
6
7
<title>BookInc</title>
8
<link rel="stylesheet" href="style.css">
9
10
</head>
11
12
<body style="background-color:white;">
13
14
<div id= "mainPage">
15
16
</div>
17
<script src="test.js"></script>
18
</body>
19
</html>