Danik
Danik

Reputation: 31

Inject additional values to select before form submission with CasperJS

I use CasperJS to submit a form and all is ok.

form code:

<form method="post" action="validation.htm">

<input id="name" type="text" value="" name="dataname"></input>
<input id="url" type="text"  value="" name="dataurl"></input>
<textarea id="desc" cols="30" rows="4" name="description"></textarea>

<select id="color" size="1" name="datacolor">
  <option value="Red">Red</option>
  <option value="Black">Black</option>
  <option value="Blue">Blue</option>
</select>

</form>

casperjs code:

casper.fill('form',
    dataname: 'Anton',
    dataurl: 'http://example.com',
    description: 'testing text...',
    datacolor: 'Blue'
, 1);

But now I need to push value to datacolor that is not listed on page.

so, something like this:

casper.fill('form',
    dataname: 'Anton',
    dataurl: 'http://example.com',
    description: 'testing text...',
    datacolor: 'Yellow'
,1);

But of course it does not work, is there any way how this can be done using CasperJS?

Upvotes: 0

Views: 673

Answers (2)

Artjom B.
Artjom B.

Reputation: 61892

You can use casper.evaluate to add a new option to the select before you submit it. You can execute plain javascript in the page and manipulate it to your liking.

casper.evaluate(function(){
    var o = document.createElement("option");
    o.setAttribute("value", "Yellow"); // what is sent to the server
    o.innerHTML = "Yellow"; // what is shown to the user
    document.querySelector("#color").appendChild(o);
});

casper.fill('form', {
    dataname: 'Anton',
    dataurl: 'http://example.com',
    description: 'testing text...',
    datacolor: 'Yellow'
}, true);

Note: Your syntax is a bit off, you forgot the { ... } around the form fields in your casperjs snippet.

Upvotes: 1

sudipto
sudipto

Reputation: 2482

This is actually an option that HTML would not provide. You cannot provide a custom value for the dropdown.

Read: HTML select form with option to enter custom value

However, you can put a hidden input (with the desired name) and pass your custom color through that.

<input type="hidden" name="datacolor" />
<select id="color" size="1" name="_datacolor">
  <option value="Red">Red</option>
  <option value="Black">Black</option>
  <option value="Blue">Blue</option>
</select>

Change the name of the <select> and use fill.

casper.fill('form',{
        dataname: 'Anton',
        dataurl: 'http://example.com',
        description: 'testing text...',
            datacolor: 'mycolor'
}
   , true);

NOTE: More handling is required using client-side JavaScript to fill up the hidden input when a value from dropdown is selected.

Upvotes: 1

Related Questions