Getting and setting text selection in a text field

I want to create a text box where users can select a piece of text, and I will respond according to their choice. Therefore i need

1) get the start and end positions of the selection text

2) get the focus position if it is in the text box and there is no choice

It seems that the functions for this differ from conductor to another. So can someone tell me what the approach can be done in the Office add-in?

I tried the following two ways (i.e., select a piece of text in myTextarea, click button, and then debug the code), they don't seem to be the right functions.

(function() {
    "use strict";

    Office.initialize = function(reason) {
        $(document).ready(function() {
            app.initialize();
            $('#button').click(showSelection);
        });
    };

    function showSelection() {
        // way 1
        console.log(document.selection); // undefined
        document.getElementById("myTextarea").focus();
        var sel = document.selection.createRange(); // Uncaught TypeError: Cannot read property 'createRange' of undefined
        selectedText = sel.text;
        // way 2 
        console.log(document.getElementById("myTextarea").selectionstart); // undefined
        console.log(document.getElementById("myTextarea").selectionend); // undefined
    }
})();

It would also be great if you could also tell me how to implement the following code:

1) ,

2)

1:

window.getSelection() Excel:

function showselection() {
    var a = window.getSelection();
    var b = window.getSelection().toString();
    var c = window.getSelection().getRangeAt(0);
}

button, : a a = Selection {anchorNode: null, anchorOffset: 0, focusNode: null, focusOffset: 0, is ...; "", Home.js:19 Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index. , ...

JSBin Excel, , .

+4
3

JQuery.

, :

function showselection() {
    console.log($('#myTextarea')[0].selectionStart);
    console.log($('#myTextarea')[0].selectionEnd);
}

:

https://github.com/localhost/jquery-fieldselection

http://madapaja.imtqy.com/jquery.selection/

( ). API , , JQuery .

+1

- HTML ( Excel/Word), fooobar.com/questions/1642507/....

+1

JavaScript API Office , (, showSelection(), ). Excel Word JS API, , . , :

Word.run(function (context) {
    var myRange = context.document.getSelection();
    context.load(myRange, 'text');
    return context.sync().then(function () {
        log("Selection contents: " + myRange.text);
    });
})

Then for other features of your question, please clarify in accordance with the requirements of my comment. Thank!

-Michael (PM for Office Add-ins)

0
source