title: Dynamically set onKeyUp attribute with Javascript
body: <p>I'm currently writing a <code>JS code</code> to calculate a running total of numeric inputs. The problem I have is that for my actual project I can't change the HTML directly as it is generated from a scripting programme. I can however manipulate it with <code>JS</code>.</p>
  
  <p>so far I've got a div to add which can show the sum of the inputs. But this only works if the inputs have an <code>onKeyUp()</code> attribute. This isn't true for the generated HTML so I need to write a <code>JS script</code> which adds it in. This is what I've done so far:</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script&gt;
      //try to set an onKeyUp attribute to the elements.
      var number1 = document.getElementById("_Q0_Q0_Q0");
      number1.onkeyup = function(){ return summer()};
  
      var number2 = document.getElementById("_Q0_Q0_Q1");
      number2.onkeyup = function(){ return summer()};
  
      var number3 = document.getElementById("_Q0_Q0_Q2");
      number3.onkeyup = function(){ return summer()};
  
      function summer() {
          var count = 0; //start with nothing
          var num1 = (parseFloat(document.getElementById("_Q0_Q0_Q0").value)) || 0; //if there aren't any numbers, add nothing
          var num2 = (parseFloat(document.getElementById("_Q0_Q0_Q1").value)) || 0;
          var num3 = (parseFloat(document.getElementById("_Q0_Q0_Q2").value)) || 0;
          count = num1+num2+num3; //sum them up
          if (!document.getElementById("output")) { //check to see if there is a div with the output already, if not create one.
          var newDiv = document.createElement('div');
          newDiv.setAttribute('id', 'output');
          var gutterDiv = document.getElementById("right_gutter")
          gutterDiv.appendChild(newDiv);
          };
          document.getElementById("output").innerHTML = "Your running total = "+count
  }; //show output
  &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  &lt;input type="text" id="_Q0_Q0_Q0" name="number" /&gt;
  &lt;input type="text" id="_Q0_Q0_Q1" name="number" /&gt;
  &lt;input type="text" id="_Q0_Q0_Q2" name="number" /&gt;
  &lt;div id='right_gutter'&gt;
  &lt;button type="button" onclick="summer()"&gt;Clicking here adds your input to the "count" variable&lt;/button&gt; //two purposes of this. 1) Acts as a placeholder for where the output should end up. 2) Shows that the summing function works.
  &lt;/div&gt;
  &lt;br&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>