inputcomponentsblazorhighlightselectedtext

Select characters (highlight text) in input on mousedown and mouseup with Blazor Component


Same thing as Javascript Window.GetSelection. Basically I want to be able to grab the selected text in an html input with Blazor.

<input type="text" value="" />

So whatever value is written into the input, upon mouse-selection will be stored in a string

string mySelectedText { get; set; }

So the user will do this: user select text from input

and the variable will hold this:

mySelectedText = "selection is made";

Dom-manipulation should be done with @on as shown in this list but i cannot see any @onSelection in that list

I have tried this suggestion without any success. The user-event must be mouse-selection of text from input, and the selected text must be stored or showed.


Solution

  • The solution is to combine Javascript with Blazor with the @inject IJSRuntime

    in the Blazor-component:

    @inject IJSRuntime js            
         <p @onmouseup="@GetSelectedText">Make selection with mouse on here</p>        
         <p>You highlighted: @SelectedText</p>
    @code {
        public string SelectedText { get; set; }
    
        async Task GetSelectedText()
        {
            SelectedText = await js.InvokeAsync<string>("getSelectedText");
        }
    }
    

    and the javascript funktion named getSelectedText in the wwwroot/html.html insert this below the webassembly.js

    <script>
    function getSelectedText() {
        return window.getSelection().toString();
    }
    </script>
    

    This solves the problem