title: Check if a form input exists
body: <p>I want to check if an input tag named "field2" exists when the user is filling out input name "field1". I do that by executing a JavaScript function using the <code>onchange</code> event on field1's <code>input</code> tag. (I'm testing using alert boxes.) If field2 does not exist, JavaScript clicks a button and the form is updated to have both field1 and field2. But the alert box pops up even when field2 exists no matter which of the 3 methods I use. I tried all sorts of combinations using <code>if</code> with <code>null</code> and <code>'undefined'</code>, etc.</p>
  
  <p>Why do the alert boxes pop up if field2 exists ?</p>
  
  
  
  <pre class="lang-js prettyprint-override"><code>function foobar(){
  
  if(!document.getElementsByName("field2"){
  alert("foobar");
  }
  
  if(!document.forms[0].field2){
  alert("foobar");
  }
  
  if(!document.forms[0].elements.namedItem("field2"){
  alert("foobar");
  }
  }
  </code></pre>