title: Javascript- Assign element id to event listener from function variable
body: <p>I'm trying to make it so I don't have a write a function for every input field I want to use this on. Rather sending the element id to the function and only having one function that I can recycle.</p>
  
  <p>Works like this</p>
  
  <pre><code>    &lt;input name="field" id="field" type="text" onKeyPress="onlyNum()" /&gt;
  
      &lt;script type="text/javascript"&gt; 
          function onlyNum() {
              var name = $("#field");
              name.keypress(function (e) {
                  if (e.which &gt; 0 &amp;&amp; // check that key code exists
                      e.which != 8 &amp;&amp; // allow backspace
                      !(e.which &gt;= 48 &amp;&amp; e.which &lt;= 57) // allow 0-9
                      ) {
                      e.preventDefault();
                  }
              });
          }
      &lt;/script&gt;
  </code></pre>
  
  <p>But it doesn't work like this, however this is what I'm going for: </p>
  
  <pre><code>    &lt;input name="field" id="field" type="text" onKeyPress="onlyNum('field')" /&gt;
  
      &lt;script type="text/javascript"&gt; 
          function onlyNum(theInput) {
              var name = document.getElementById(theInput);
              name.keypress(function (e) {
                  if (e.which &gt; 0 &amp;&amp; // check that key code exists
                      e.which != 8 &amp;&amp; // allow backspace
                      !(e.which &gt;= 48 &amp;&amp; e.which &lt;= 57) // allow 0-9
                      ) {
                      e.preventDefault();
                  }
              });
          }
      &lt;/script&gt;
  </code></pre>
  
  <p>So does anyone know what's wrong with the second example? And how can I get that to work. Thanks</p>