1

I'm trying to select text within a textarea using Cypress, but running into some issues. The Cypress api doesn't have an out of the box way to do it that I can find, so I tried implementing it myself.

I found this stackoverflow answer about selecting text and decided to follow its example. What I've arrived at is this:

selectTextWithin = (selector: string) => {
    cy.document().then((doc: Document) => {
        cy.window().then((win: Window) => {
            cy.get(selector).then((textElement: JQuery<HTMLElement>) => {
                if (win.getSelection) {
                    const selection = win.getSelection();
                    const range = doc.createRange();
                    range.selectNodeContents(textElement.get(0));
                    selection.removeAllRanges();
                    selection.addRange(range);
                } else {
                    throw new Error("Can't select text.")
                }
            })
        })
    })
}

It executes without error, but it doesn't appear to be selecting any text.

CorayThan
  • 17,174
  • 28
  • 113
  • 161
  • 2
    If you want to select the entire contents then it's just `textElement.get(0).select()`. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select – Alexey Lebedev Aug 06 '18 at 20:00

1 Answers1

3

The answer you linked to deals with selecting text specifically outside an input field. Here is an answer for selecting text in an input field.


They posted a demo, and I've modified it for Cypress.

HTML:

<html>
  <body>
    <textarea type="textarea" name="message" id="message">Hello World</textarea>
  </body>
</html>

Cypress:

function createSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
}

describe('Text selection', function() {
    it('Selects text in a text area', function() {
        cy.get("#message").then(textarea => {
            createSelection(textarea, 0, 5);
        });
    }
}
Joshua Wade
  • 4,755
  • 2
  • 24
  • 44
  • I appreciate it! That's a silly mistake. Should've looked at the code snippet. @Alexey Lebedev's comment solves my specific issue more easily, but your answer is much more complete. – CorayThan Aug 07 '18 at 21:20
  • No problem! Yeah, if you just want to select all the text, it's much simpler. – Joshua Wade Aug 08 '18 at 13:09