title: PhantomJS and clicking a form button
body: <p>I have a very simple HTML form that I'm attempting to test with various kinds of data.  I wrote a prototype proof-of-concept in MS Access/VBA using the IE object.  It worked fine but the finished testing product has to use PhantomJS.  I've got the page-interfacing to work and the form is populating just fine.  Where I'm stuck is getting the submit button to fire.  I've combed through S.O. and tried all suggestions and nothing is working.  I'm using PhantomJS 1.9.7 and using straight JavaScript test scripts. </p>
  
  <p>I tried various JavaScript techniques to fire the submit button.  To satisfy the "Just use JQuery" crowd, I tried that too.  Nothing is working.  When I render the form at the end of the test script, I see the form populated with data patiently waiting for the &lt;search&gt; button to be clicked.</p>
  
  <p>Here's a summary of what I tried:</p>
  
  <ol>
  <li><code>document.getElementById('btnSearch').click();</code> </li>
  <li><code>$("btnSearch").click();</code>  </li>
  <li><code>var el = document.getElementById('btnSearch'); // Get search button object</code>
  <br><code>$(el).click();</code> </li>
  <li><code>document.getElementById('Form1').submit();</code></li>
  <li>Tried creating a click event and firing it from the button object (in the code below)</li>
  <li>Tried creating a click event and firing it from the <em>body</em> object with the coordinates of a point inside the button in question</li>
  </ol>
  
  <p>Here's the form: 
  (And please, no comments/debates on the lack of CSS, use of tables, etc. I have no say or influence over the people who created the site.)</p>
  
  <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  &lt;HTML&gt;
      &lt;HEAD&gt;
          &lt;title&gt;Da Site&lt;/title&gt;
      &lt;/HEAD&gt;
      &lt;body&gt;
      &lt;form name="Form1" method="post" action="Default.aspx" id="Form1"&gt;
      &lt;TABLE id="Table2" cellSpacing="2" cellPadding="1" border="0"&gt;
        &lt;TR&gt;
          &lt;TD&gt;Street Address:&lt;/TD&gt;
          &lt;TD&gt;&lt;input name="Address" type="text" maxlength="100" id="Address" /&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
          &lt;TD&gt;City:&lt;/TD&gt;
          &lt;TD&gt;&lt;input name="City" type="text" maxlength="100" id="City" style="width:232px;"/&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
          &lt;TD&gt;State:&lt;/TD&gt;
          &lt;TD&gt;&lt;select name="State" id="State"&gt;
                      &lt;option value=""&gt;&lt;/option&gt;
                      &lt;option value="AL"&gt;AL - Alabama&lt;/option&gt;
                      &lt;option value="AK"&gt;AK - Alaska&lt;/option&gt;
                      [The rest of the other states]
                      &lt;option value="WI"&gt;WI - Wisconsin&lt;/option&gt;
                      &lt;option value="WY"&gt;WY - Wyoming&lt;/option&gt;
                      &lt;option value="PR"&gt;PR - Puerto Rico&lt;/option&gt;
              &lt;/select&gt;
          &lt;/TD&gt;
        &lt;/TR&gt;
        &lt;TR&gt;
          &lt;TD&gt;Zip Code:&lt;/TD&gt;
          &lt;TD&gt;&lt;input name="ZipCode" type="text" maxlength="5" id="ZipCode" /&gt;&lt;/TD&gt;
        &lt;/TR&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;input type="submit" name="btnSearch" value="Search" id="btnSearch" /&gt;
              &lt;input type="submit" name="btnReset" value="Reset" id="btnReset" /&gt;
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/TABLE&gt;
      &lt;/form&gt;
      &lt;/body&gt;
  &lt;/HTML&gt;
  </code></pre>
  
  <p>Here's the JavaScript to drive the form:</p>
  
  <pre><code>var maxtimeOutMillis = 3000;
  var start;
  var finish;
  
  var page = require('webpage').create();
  
  // Route "console.log()" calls from within the Page context to the main Phantom context (i.e. current "this")
  page.onConsoleMessage = function(msg) {
                                        console.log(msg);
                                        };
  
  page.open('http://www.MadeUpURL.com/', function(status) {
  
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
  
    if (status !== 'success') {
      console.log('Unable to access network');
    } else {
           page.render('before.png');  // Renders the blank form
           page.evaluate(
                function () {
                            // page.render('Sample.png');
                            document.getElementById('Address').value = '123 Somewhere Drive';
                            document.getElementById('City').value = 'Somewhere';
                            document.getElementById('State').selectedIndex = 36;
                            document.getElementById('ZipCode').value = '12345';
  
           // I've done a page.render() here and it shows the form fully and correctly populated
  
                            // Now let's submit the form...
                            var el = document.getElementById('btnSearch');   // Get the "search" button object
  
                            // Tried the usual suspects
                            document.getElementById('btnSearch').click();
                            $("btnSearch").click();
                            $(el).click();
                            document.getElementById('Form1').submit();
  
                            // Tried creating a click event and firing it from the button object
                            var ev = document.createEvent("MouseEvent");
                            ev.initMouseEvent("click",
                                              true /* bubble */,
                                              true /* cancelable */,
                                              window,
                                              null,
                                              0, 0, 0, 0, /* coordinates */
                                              false, false, false, false, /* modifier keys */
                                              0 /*left click*/,
                                              null);
                            el.dispatchEvent(ev);
  
                            // Tried calculating the location of the button itself (which works) and fire the click event from the &lt;Body&gt; object
                            var obj = document.getElementById('btnSearch');
                            var x = obj.offsetLeft;
                            var y = obj.offsetTop;
  
                            while (obj.offsetParent) {
                              x = x + obj.offsetParent.offsetLeft;
                              y = y + obj.offsetParent.offsetTop;
                              if (obj == document.getElementsByTagName("body")[0])
                                {
                                  break;
                                }
                                else
                                {
                                  obj = obj.offsetParent;
                                }
                              }
  
                            x = x + 5; // Tried with and without this +5 delta
                            y = y + 5; // Tried with and without this +5 delta
  
                            console.log('X = ' + x);
                            console.log('Y = ' + y);
  
                            var ev = document.createEvent("MouseEvent");
                            ev.initMouseEvent("click",
                                              true /* bubble */,
                                              true /* cancelable */,
                                              window,
                                              null,
                                              0, 0, x, y, /* coordinates */
                                              false, false, false, false, /* modifier keys */
                                              0 /*left click*/,
                                              null);
                            document.body.dispatchEvent(ev);
  
                            });
           start = new Date().getTime();
           finish = new Date().getTime();
           console.log('Time before: ' + start);
           // Check to see if results are defined (or times out)
           while ( (finish - start &lt; maxtimeOutMillis) &amp;&amp;  !( page.evaluate( function() {return document.getElementById('TheAnswer');})))
             {
             finish = new Date().getTime();
             }
           console.log('Time after: ' + finish);
           if ( page.evaluate( function() {return document.getElementById('TheAnswer');}))
             {
             console.log(page.evaluate( function() {return document.getElementById('TheAnswer').textContent;}));
             }
           else
             {
             console.log('Element not defined');
             }
           }
    page.render('after.png');
    phantom.exit();
  
    });
  
  });
  </code></pre>
  
  <p>I'm hoping this is one of those you-forgot-a-semicolon kind of things, but I just don't see it.  Any help would be very much appreciated!</p>
  
  <p><strong>Edit #1:</strong> Adding the script output for reference.</p>
  
  <pre><code>C:\Temp\WebAutomation\PhantomJS\scripts&gt;phantomjs interact.js
  X = 151
  Y = 442
  Time before: 1407875912197   [edit #2 - change before/after labels to match code]
  Time after: 1407875915197
  Element not defined
  C:\Temp\WebAutomation\PhantomJS\scripts&gt;
  </code></pre>