CasperJS / Javascript Selecting Multiple Options

Trying to clean a website where this is common HTML

<select id="xxx" multiple name="zzz">
<option value="123">xaxaxa</option>
<option value="124">zazaza</option>
<option value="125">ajajaj</option>
<option value="126">azzzsa</option>
</select>

It is not enclosed in a form, so I tried to use the fill () function that casperjs provides, but that did not work.

For individual entries, I would usually use casper.click (), and this would work, but it does not work for multiple entries, even with a loop

In addition, the website I am trying to clear holds “shift” to select multiple elements, but then this can be done by dragging and selecting.

I need to select multiple values

+4
source share
1 answer

This is easily done by setting a property selectedfor each element of the parameter true.

CasperJS by value

casper.selectOptionsByValues = function(selectCssSelector, values){
    this.evaluate(function(selector, values){
        [].forEach.call(document.querySelector(selector).options, function(opt){
            if (values.indexOf(opt.value) !== -1) {
                opt.selected = true;
            }
        });
    }, selectCssSelector, values);
};

. :

casper.selectOptionsByValues("#xxx", [ "124", "125" ]);

CasperJS

:

casper.selectOptionsByTexts = function(selectCssSelector, texts){
    texts = texts.map(function(t){ return t.trim() });
    this.evaluate(function(selector, texts){
        [].forEach.call(document.querySelector(selector).options, function(opt){
            if (texts.indexOf(opt.text.trim()) !== -1) {
                opt.selected = true;
            }
        });
    }, selectCssSelector, texts);
};

:

casper.selectOptionsByTexts ("#xxx", [ "zazaza", "ajajaj" ]);

PhantomJS

PhantomJS:

function selectOptionsByValues(page, selectCssSelector, values){
    page.evaluate(function(selector, values){
        [].forEach.call(document.querySelector(selector).options, function(opt){
            if (values.indexOf(opt.value) !== -1) {
                opt.selected = true;
            }
        });
    }, selectCssSelector, values);
};

:

selectOptionsByValues(page, "#xxx", [ "124", "125" ]);

,

this.evaluate(function(selector, values){
    [].forEach.call(...);

    var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
    evt.initUIEvent("change", true, true);
    document.querySelector(selector).dispatchEvent(evt);
}, selectCssSelector, values);

.

+3

All Articles