Search code examples
javascriptdomcasperjs

Using Casperjs to Submit Form with no ID or Name


This is my first time working with Casperjs. I have a form which has no id or name but does require a user name and password to be submitted.

In the HTML body there is an onload="init(document.forms[0]);"

The form:

<form method="post">
                <table border="0" cellspacing="0" cellpadding="0">
                        <tbody><tr>
                        <script>
                                document.write('<td class="username">');
                                document.write(langstr[ui_CurrentLanguage].login_username);
                                document.write('&nbsp;:&nbsp;');
                                document.write('</span>');
                                document.write('<td colspan="2"><input type="text" class="inputname" id="user_name" name="user_name" onKeyPress="if(event.keyCode == \'13\') Validate();" size="20" maxlength="65" autocomplete="off"></td>');
                        </script><td class="username">USERNAME&nbsp;:&nbsp;</td><td colspan="2"><input type="text" class="inputname" id="user_name" name="user_name" onkeypress="if(event.keyCode == '13') Validate();" size="20" maxlength="65" autocomplete="off"></td>
                        </tr>
                        <tr>
                        <script>
                                document.write('<td class="password">');
                                document.write(langstr[ui_CurrentLanguage].login_password);
                                document.write('&nbsp;:&nbsp;');
                                document.write('</span>');
                                document.write('<td colspan="2"><input type="password" class="inputpwd" id="user_passwd" name="user_passwd" onKeyPress="if(event.keyCode == \'13\') Validate();" size="20" maxlength="64" autocomplete="off"></td>');
                        </script><td class="password">PASSWORD&nbsp;:&nbsp;</td><td colspan="2"><input type="password" class="inputpwd" id="user_passwd" name="user_passwd" onkeypress="if(event.keyCode == '13') Validate();" size="20" maxlength="64" autocomplete="off"></td>
                        </tr>
                </tbody></table>

I'm having trouble referencing the form so that I can use the fill method in casperjs. Any ideas on how to get a reference to this form?

Thanks.


Solution

  • You need to use sendKeys() to fill the form and send the key "13" (Enter):

    var casper = require('casper').create(), utils = require('utils');
        casper
    
    .start('http://',function(){
        this.sendKeys('#user_name',  'your_name', {keepFocus: true});
        this.sendKeys('#user_passwd','your_pass', {keepFocus: true});
        this.sendKeys('#user_passwd', casper.page.event.key.Enter , {keepFocus: true});
    
        this.wait(3000,function(){
        this.capture('test.png');
        utils.dump(this.getTitle());
    });
    })
        .run();
    

    See also: this issue