postgresnewbie
postgresnewbie

Reputation: 1468

unwanted situations after creating button in javascript

I need to create a button dynamically with javascript. so i wrote these codes in between "script" tags.

window.onload = function () {
    var newButton = document.createElement('input');
    newButton.type = 'button';
    newButton.value = 'What's the day today?';
    newButton.id = 'btn1';
    newButton.onclick = myfunction();
    div1.appendChild(newButton);
}
function myfunction() {
    var x = new Date().getDay();
    switch (x) {
        case 0: alert("sunday"); break;
        case 1: alert("monday"); break;
        case 2: alert("tuesday"); break;
        case 3: alert("wednesday"); break;
        case 4: alert("thursday"); break;
        case 5: alert("friday"); break;
        case 6: alert("saturday"); break;

    }
}

when the page is loaded, "myfunction()" function is running automatically. after that when i press this button, nothing happens. what's my mistake?

Upvotes: 0

Views: 53

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

You need to change

newButton.onclick = myfunction;

When you do newButton.onclick = myfunction(); it executes the myfunction and then assigns the value returned by it to the onclick handler, in this case undefined. What you need to do is to pass the function reference to the onclick property

Also I assume the following is a copy paste change

newButton.value = 'What's the day today?'; // you need to escape ' with \' or use "What's the day today?"

Upvotes: 2

Related Questions