Zillon
Zillon

Reputation: 73

Protractor: Ctrl Click

I am trying to select multiple elements on my page using ctrl click on successive elements. This functionality works fine when done manually, but I am having some troubles with its automation using protractor.

This is my ptor function:

this.selectElements = function (names) {
    for(var i = 0; i < names.length; i++){
        var parentElement = element(by.xpath('//div[@aria-label="select group ' + names[i] + '"]'));
        browser.wait(EC.presenceOf(parentElement), DEFAULT_WAIT_TIMEOUT);
        browser.actions()
            .mouseMove(parentElement).perform();
        browser.sleep(500);
        browser.actions().keyDown(protractor.Key.CONTROL)
            .click()
            .perform();
    }

So for each value in names it gets the element in the DOM, moves the mouse on it, sleeps then ctrl clicks.

The result of calling this function on six elements is as follows, the following elements are selected:

In other words it selects at most two elements, then deselects all and selects again at most two. Any idea what is going on there?

Additional question: is it possible to send these actions directly to the element(instead of using browser.actions())? It seems that only keyboard keys OR mouse actions can be sent to elements, but not both at once (something like sendKeys().click()).

Upvotes: 2

Views: 966

Answers (1)

Sudharsan Selvaraj
Sudharsan Selvaraj

Reputation: 4832

The problem is, you are executing the actions sequence for each loop by calling perform() method. Instead, you need to chain all-action sequence in the loop and then execute it at last. Try the below example,

this.selectElements = function (names) {
    var actionSequence = browser.actions().keyDown(protractor.Key.CONTROL);
    for(var i = 0; i < names.length; i++){
        var parentElement = element(by.xpath('//div[@aria-label="select group ' + names[i] + '"]'));
        actionSequence = actionSequence.mouseMove(parentElement).click();
    }
    actionSequence.perform();
}

Upvotes: 3

Related Questions