Search code examples
javascripthtmldominputappendchild

Dynamically generating a button using DOM and editing onclick event


I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.

I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.

What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!

[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)

<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();

function addButton() {
    i++;
    var container = document.getElementById("check0");

    var h[i] = document.createElement("input");
    h[i].type = 'button';
    h[i].name = 'number' + i;
    h[i].value = "number" + i;
    h[i].id = 'number' + i;

    h[i].onclick = function() {
        showAlert(i)
    };

    container.appendChild(h[i]);
}

function showAlert(number) {
    alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
        <input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>

Solution

  • Here is the fixed fiddle for you.

    • var h[i] = ... is invalid JavaScript.
    • What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).

      <script>
      var i = 0;
      var h = new Array();
      
      function addButton() {
          i++;
          var container = document.getElementById("check0");
      
          h[i] = document.createElement("input");
          h[i].type = 'button';
          h[i].name = 'number' + i;
          h[i].value = "number" + i;
          h[i].id = 'number' + i;
      
          h[i].onclick = function() {
              showAlert(i)
          };
      
          container.appendChild(h[i]);
      }
      
      function showAlert(number) {
          alert("You clicked Button " + number);
      }
      </script>
      
      <div id="check0">
          <input type="button" value="klick mich" id="number0" onclick="addButton()"/>
      </div>​