The following code successfully adds a button to a form every time I click a button with id "button0". But firebug gives me the error
form1 is null
[Break On This Error]
form1.appendChild(element);
And the new button will not execute the function "foo()" despite the fact that it's been set to its onclick value. Here's the code
var counter = 0;
function add(){
counter++;
var element = document.createElement("input");
element.type = "button";
element.value = "test";
element.name = "button"+counter;
element.id = "button"+ counter;
element.onclick="foo()";
var form1 = document.getElementById("form1");
var body1 = document.getElementById("b1");
var header = document.getElementById("header");
form1.appendChild(element);
header.innerHTML = "Two Buttons";
};
function foo(){
var butt = document.getElementById("button1");
butt.value = "works";
console.log("works");
};
add();
I also get a firebug error (undefined) if I use document.form1.appendChild(element);
The funny thing is I DO get the new button every time I click. It's just that the button doesn't work.
Here's my html
<body id = "b1">
<script src = "button-in-code.js"></script>
<h1 id = "header">Buttons</h1>
<form id = "form1" name = "form1">
<input type="button" id = "button0" name="sel" value="Select all" onclick="add()">
</form>
<hr>
<address></address>
<!-- hhmts start -->Last modified: Mon Jul 8 10:07:26 EDT 2013 <!-- hhmts end -->
</body> </html>
form1, this may be an html issue. It may also help to set this up on a site like jsfiddle.net or jsbin.com.onclick, not a string.