Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I'm trying to get the currently selected text in input using window.getSelection() but I'm always getting an empty string:

expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");

Results into:

Expected '' to equal 'test'.

The complete reproducible test using angularjs.org as a target site:

describe("My test", function () {

    beforeEach(function () {

        browser.get("https://angularjs.org/");

    });

    it("should select text in an input", function () {

        var query = element(by.css("input.search-query"));

        query.sendKeys("test");

        query.sendKeys(protractor.Key.chord(protractor.Key.COMMAND, "a"));

        expect(browser.executeScript("return window.getSelection().toString();")).toEqual("test");

    });

});

Note that I actually see the entered text being selected with COMMAND + "a".

What am I doing wrong?

Using protractor 2.5.1, firefox 41.

1 Answer

0 votes
by (62.9k points)

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

If the value for an option is not defined specifically, the text content of the <option> element will be used as a value instead, as shown in the following code:

 

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>jQuery Get Selected Option Text</title>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){

    $("select.country").change(function(){

        var selectedCountry = $(this).children("option:selected").val();

        alert("You have selected the country - " + selectedCountry);

    });

});

</script>

</head> 

<body>

    <form>

        <label>Select Country:</label>

        <select class="country">

            <option>United States</option>

            <option>India</option>

            <option>United Kingdom</option>

        </select>

    </form>

</body>

</html>

Alternatively, you can use the jQuery text() method to get the text content of an element.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...