2

Hi allm I would like to know how to get an input value with casperjs

This is my html element

<input type="hidden" name="key" value="newkey">

This is what I have tried:

    view            = 'users/registered';

    casper.test.begin("Activating account", 5, function register(test){
        casper.start(webroot + view, function(){

        }).then(function(){
            this.echo("Retrieving data from hidden input key", "COMMENT");

            activationKey = this.evaluate(function() {
                return __utils__.getFieldValue('key');
            });

        }).then(function(){
            this.echo("Activating account with the key \"" + activationKey + "\"", "COMMENT");
            window.location = webroot + activationKey;
        });

        casper.run(function() {
            this.echo('Account activated successfully', 'SUCCESS').exit();
            test.done();
        });
    });

casper.viewport(page.width, page.height);

In this case return null

I have also tried:

activationKey = __utils__.getFieldValue('key');

but return me this error:

FAIL ReferenceError: Can't find variable: __utils__
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171

2 Answers2

11

Try using this :

this.getElementAttribute('input[type="hidden"][name="key"]', 'value');
Fanch
  • 3,274
  • 3
  • 20
  • 51
  • 2
    for some reason, for me this.getElementAttribute("#myId", "value") doesn't work, whereas this.evaluate(function(){ return document.getElementById("myId").value;}) does. Any idea why ? – Vic Seedoubleyew May 03 '16 at 18:04
  • @VicSeedoubleyew Sadly no, it should work in both cases ^^. – Fanch May 04 '16 at 12:14
  • @VicSeedoubleyew, I suspect it doesn't work because getElementAttribute doesn't work with dynamic values (i.e. values that are set after the page is loaded). I'll add another answer here that works when form values are set dynamically. – l p Nov 14 '16 at 04:05
5

If the value is set dynamically, then this.getElementAttribute won't work, nor will __utils__.getFieldValue. The only way, as of 1.1.3, is to call the underlying document object's querySelector.

  var value = this.evaluate(function() {
    return document.querySelector('[name="key"]').value
  })

A bit verbose, but at least it works.

Also, regarding why __utils__ couldn't be found, use the following to import it:

var __utils__ = require('clientutils').create()

In the OP's example, __utils__ is in the evaluate() function. It shouldn't be, as __utils__ is a casper thing, not a DOM/javascript thing.

l p
  • 528
  • 1
  • 7
  • 17
  • This unrelated answer has some more insight has to why getting a value using get*Attribute won't always give you what you expect: http://stackoverflow.com/a/10280487/4978821 – l p Nov 14 '16 at 16:35