user3282537
user3282537

Reputation: 99

How can i call a function on run time on button click as you can see in below code

function createButton(){
    var btnDisplay = document.createElement("button");
    btnDisplay.innerHTML="Display Value";
    btnDisplay.backgroundColor="green";
    btnDisplay.onclick="alrt()";
    var divCon = document.getElementById("detailcal");
    divCon.appendChild(btnDisplay);

}

Here I am create crate a function that create a button and I have set a attribute for it, attribute is displaying on a page but function alrt(); is not displaying on page code.

not working any solution to do it.

Upvotes: 2

Views: 120

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

IMO it's better if you could avoid inlin-events and use addEventListener() or onclick instead :

btnDisplay.onclick=function() { alrt();  };
//OR
btnDisplay.addEventListener('click', alrt, false);

Hopet this helps.

Upvotes: 1

madox2
madox2

Reputation: 51861

You can use setAttribute method of element:

function createButton(){
    var btnDisplay = document.createElement("button");
    btnDisplay.innerHTML="Display Value";
    btnDisplay.backgroundColor="green";
    btnDisplay.setAttribute("onclick", "alert('hello')");
    var divCon = document.getElementById("detailcal");
    divCon.appendChild(btnDisplay);

}
createButton();

Upvotes: 1

Related Questions