Frans B
Frans B

Reputation: 65

Why isn't this on.Click working on my button

///// FORM  ////
var form = document.getElementById("form");
form.setAttribute("style", "position: relative; margin-bottom: 5%;");

var newButton = document.createElement('button');
var newUl = document.createElement('ul');
var newLi = document.createElement('li');
var newInput = document.createElement('input');
form.appendChild(newButton);
newButton.setAttribute("style", "position: absolute; width: 15%; height: 40px; left: 42%; color: #B00000; background-color: white; font-size: 18px; border: 0px; ");
newButton.innerHTML = "Direct Message";
newButton.onClick = function() {
  alert("works");
};

Is there something wrong with my selection? just want the on.click to work on my button which is newButton created element.

Upvotes: 0

Views: 47

Answers (3)

Daniel Developer
Daniel Developer

Reputation: 1

this code doesn't work because the syntax is incorrect.

the correct syntax about the event 'click' is below:

newButton.onclick = function(){
 alert("works");
};

the event is write on the lower case.

Upvotes: 0

Pointy
Pointy

Reputation: 413727

Two things:

  1. You need to set the "type" attribute of the button to "button";
  2. It's "onclick", not "onClick"

The first thing prevents the button from submitting the surrounding <form> when it's clicked. The second will correctly set up the event handler.

Upvotes: 0

Barmar
Barmar

Reputation: 781058

Javascript property names are case-sensitive, it should be newButton.onclick.

Or you could move into the modern age and use addEventListener.

newButton.addEventListener("click", function() {
    alert("works");
});

Upvotes: 2

Related Questions