How can I create a dynamic button with a click event with JavaScript?
I tried this, but when I click the add button, an alert message show up! It's not what I want - I want to be able to click the button which is dynamically created.
<script language="javascript">
function add(type) {
//Create an input type dynamically.
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
element.setAttribute("onclick", alert("blabla"));
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
</script>
This question is related to
javascript
html
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.setAttribute("onclick", alert("clicked"));
}
</script>
</body>
</html>
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
this:
element.setAttribute("onclick", alert("blabla"));
should be:
element.onclick = function () {
alert("blabla");
}
Because you call alert instead push alert as string in attribute
Source: Stackoverflow.com