1

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.

Villads Claes
  • 111
  • 10
  • Does this answer your question? [Get the selected text from an input using Blazor](https://stackoverflow.com/questions/60110779/get-the-selected-text-from-an-input-using-blazor) – Quango Nov 27 '20 at 11:20
  • No, @Quango, unfortunatly not. I tried to copy the code from your linked page to a component. I cannot even see what the code does. In other words i need to see a working example or documentation on the way to select highligthed text. – Villads Claes Nov 27 '20 at 12:55

1 Answers1

2

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

Villads Claes
  • 111
  • 10