Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the selected text from an input using Blazor

In an early version of Blazor there was an IHtmlInputElement interface with selectionStart and selectionEnd properties.

Can anyone explain how I can use these to get the selected text from a text input control in C#?

UPDATE Here's what I have so far.

@page "/selectedtext"
@inject IJSRuntime JsRuntime

<h3>TextSelection</h3>

<input type="text" placeholder="Type here" @ref="myTextInput"/>

<button class="btn btn-primary" @onclick="@(async () => await GetSelectionStart(myTextInput))"></button>

@code {
    public ElementReference myTextInput { get; set; }

    public async Task GetSelectionStart(ElementReference element)
    {
        int pos = await JsRuntime.InvokeAsync<int>("GetSelectedStart", element);
    }
}

// myscript.js
{
    getSelectedStart : function (element) {
        return element.selectionStart;
    }
}
like image 624
phil Avatar asked Aug 06 '26 05:08

phil


1 Answers

@page "/selectedtext"
@inject IJSRuntime JsRuntime

<h3>TextSelection</h3>

<input type="text" placeholder="Type here" @ref="myTextInput"/>

<button class="btn btn-primary" @onclick="@(async () => await GetSelectionStart(myTextInput))">Get Position</button>

@code {
    public ElementReference myTextInput { get; set; }

    public async Task GetSelectionStart(ElementReference element)
    {
        int pos = await JsRuntime.InvokeAsync<int>("getSelectedStart", element);
    }
}

// myscript.js
window.getSelectedStart = (element) => {
        return element.selectionStart;
    }

like image 121
phil Avatar answered Aug 08 '26 07:08

phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!