Skip to main content

How to: Get a selected text on the client side

  • 2 minutes to read

This example demonstrates how to get selected text on the client side. The ASPxRichEdit client-side API provides the selection property that allows you to select a text range in code or obtain the selected range’s Interval object. This object can be used to receive the selected text: all text is stored within sub-documents, following the ASPxRichEdit document model structure. Thus, get an active sub-document using the client-side document property and use the text array to access the selected text range. If you need to receive all text in the active sub-document, you can get the entire text array.

<script type="text/javascript">
    function getAllText() {
        return RichEdit.document.activeSubDocument.text;
    }
    function getSelectedText() {
        var firstSelectedInterval = RichEdit.selection.intervals[0];
        var selectedText = RichEdit.document.activeSubDocument.text.substr(firstSelectedInterval.start, firstSelectedInterval.length);
        return selectedText;
    }
    function selectFirstLine() {
        return RichEdit.selection.selectLine();
    }
</script>
<dx:ASPxButton runat="server" ID="Button1" Text="Get All Text" AutoPostBack="false">
    <ClientSideEvents Click="function(s, e) { alert(getAllText()); }" />
</dx:ASPxButton>
<dx:ASPxButton runat="server" ID="Button2" Text="Get Selected Text" AutoPostBack="false">
    <ClientSideEvents Click="function(s, e) { alert(getSelectedText()); }" />
</dx:ASPxButton>

<dx:ASPxRichEdit ID="RichEdit" runat="server" ClientInstanceName="RichEdit">
    <ClientSideEvents Init="function(s, e) { selectFirstLine(); }" />
</dx:ASPxRichEdit>
using DevExpress.Web.Office;
using DevExpress.XtraRichEdit;
using System;
using System.IO;

public partial class _Default : System.Web.UI.Page {
    string documentId = "docId";

    protected void Page_Load(object sender, EventArgs e) {
        if(!IsPostBack) {
            using(MemoryStream stream = new MemoryStream()) {
                RichEditDocumentServer server = new RichEditDocumentServer();
                server.CreateNewDocument();
                server.Document.AppendText("Hello world!");
                server.Document.Paragraphs.Append();
                server.Document.AppendText("Some text...");
                server.SaveDocument(stream, DocumentFormat.OpenXml);
                stream.Position = 0;
                DocumentManager.CloseDocument(documentId);
                RichEdit.Open(documentId, DocumentFormat.OpenXml, () => stream);
            }
            RichEdit.Focus();
        }
    }
}