user3444609
user3444609

Reputation: 25

Events and handlers JavaScript

I am writing a code in which I want to display a word and sentence to my webpage when clicked(button). So far I have one text being displayed onto the page.I want to display the sentence after the text.The sentence is not displaying... anyone know why?

function handleButtonClick(){

    var button = document.getElementById("addButton");
    button.onclick = handleButtonClick;


    var textInput = document.getElementById("word");
    var termName = textInput.value;

    var dt = document.createElement("dt");
    dt.innerHTML = termName;

    var dl = document.getElementById("p");

    dl.appendChild(dt);


    var textInput = document.getElementById("sentence");
    var termDefine = textInput.value;

    var dd = document.createElement("dd");
    dd.innerHTML = termDefine;

    var dl = document.getElementById("define");

    dl.appendChild(d);


}
window.onload = handleButtonClick;

Upvotes: 1

Views: 42

Answers (2)

Andrea Scarcella
Andrea Scarcella

Reputation: 3323

In addition to what @sushanth already mentioned there is a typo in your code:

Instead of

 dl.appendChild(d);

It should be

 dl.appendChild(dd);

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55740

button.onclick = handleButtonClick;

supposed to be

button.addEventListener('click', handleButtonClick);

The second point is that the click event handler should be bound outside the function scope. Otherwise a new event will be bound every single time the function handleButtonClick fires.

var button = document.getElementById("addButton");
button.addEventListener('click', handleButtonClick);

function handleButtonClick() {
   // Your other code here
   // that excludes the click handler
}

And developer tools is your friend. Always use it to check for any errors.

Upvotes: 3

Related Questions