Victor Hugo
Victor Hugo

Reputation: 108

Create a Button in Javascript

Hey i want to create a button like this:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="click-me" id="myButton" onclick="myFunction()">
</body>
</html>

but i want to create from javascript, and i'm doing something really wrong cause my button does not seem

var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton); //i have others things working in this "Div" only this button doesn't appear

Upvotes: 1

Views: 125

Answers (4)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You've a misuse of onclick in the posted code, if you check the console you could notice the following message :

"Uncaught TypeError: MyButton.onclick is not a function"

To attach the click event using the onclick it should be :

MyButton.onclick = myFunction;

Else it will be better to attach the event using addEventListener() instead like :

MyButton.addEventListener("click", myFunction);

Hope this helps.

var Div = document.getElementById("my_div");


var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction);
Div.appendChild(MyButton);

function myFunction(){
  alert('test');
}
<div id="my_div"></div>

Upvotes: 1

Pedro Chiiip
Pedro Chiiip

Reputation: 188

In both HTML and Javascript, you are declaring your onclick function the wrong way. Instead of

<input type="button" value="click-me" id="myButton" onclick"myFunction()">

it should be

<input type="button" value="click-me" id="myButton" onclick="myFunction()">

Which means that this piece of code in Javascript here:

MyButton.onclick("myFunction()");

Should be

   MyButton.onclick = function(){ myFunction() };

By doing this and solving the typo that other users mentioned, it should work just fine.

Upvotes: 0

XYZ
XYZ

Reputation: 4480

Use addEventListener to add click event to the button; And change Div.appendChild(button); to Div.appendChild(MyButton);

function myFunction(){
  alert("here");
}

var Div = document.getElementById('div');

var MyButton = document.createElement("button");
MyButton.id = "Mybuttonid";
MyButton.innerHTML ="CLICK ME"
MyButton.className = "MyButtonclass";
MyButton.addEventListener("click", myFunction, false);
 
Div.appendChild(MyButton); //i have others think working in this "Div" only this button doesn't appear
<div id="div">
</div>

Upvotes: 0

Manos Kounelakis
Manos Kounelakis

Reputation: 3161

You are doing it wrong because Button does not exists(but MyButton exists). Instead of :

var MyButton = document.createElement("BUTTON");
MyButton.id = "Mybuttonid";
MyButton.className = "MyButtonclass";
MyButton.onclick("myFunction()");
Div.appendChild(MyButton);

Upvotes: 0

Related Questions