Button created doesn’t have onclick



Here’s my HTML:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>BookInc</title>
  <link rel="stylesheet" href="style.css">

</head>

<body style="background-color:white;">

    <div id= "mainPage">

    </div>
    <script src="test.js"></script>
</body>
</html>

and my javascript:

var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = "Negociate";
btn.onclick = console.log("hello");
document.getElementById('mainPage').appendChild(btn);

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.

Answer

onclick needs to be a function. Please see the example.

var sayHello = function(){
    console.log("hello");
};

var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = "Negociate";
btn.onclick = sayHello;
document.getElementById('mainPage').appendChild(btn);
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>BookInc</title>
  <link rel="stylesheet" href="style.css">

</head>

<body style="background-color:white;">

    <div id= "mainPage">

    </div>
    <script src="test.js"></script>
</body>
</html>


Source: stackoverflow