Search code examples
javascriptblazorblazor-client-side

Blazor, how to pass event target to JavaScript


I'd like to ask:

In Blazor, how to pass event target (or this) to my JavaScript? The thing is I'm creating inputs with @foreach so there can be a number of them.

Here is how it looks like:

@foreach (Item in ItemsList)
        {
          <input 
              @onchange="ChangeColor" 
              value="@Item.Value">
}

I want to simple onchange trigger this function:

@code 

{
    async Task ChangeColor()
    {
        await JsRuntime.InvokeVoidAsync("changeColor");
    }
}

And eventually read the value in my JS:

function changeColor (el) {


   console.log(el);

}

I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.


Solution

  • As said in the comments

    @Vencovsky I hoped to get DOM elemenet

    And if you want to show in the console the DOM element, you need to pass @ref to the DOM element and pass that reference to javascript

    But then you say in your question

    I tried using @ref, however I'd like to get access to the input that triggers the function. Since there may by many of them, I don't want to hardcode it using @ref to each of them.

    So it's kind of confusing, because you need to use @ref but you say you don't want to use @ref, so what I think is happening is that you used @ref the wrong way and you think you don't need it, but actually you do.

    Here is what you need

    • A property to hold all the refs of each element (ElementReference)
    • Pass to ChangeColor only the element that is clicked

    Here is an example on how to do it

    @for(var i = 0; i < ItemsList.Count(); i++)
    {
        var ii = i;
    
        @* Passing only the ref that called @onchange *@
        <input @onchange="(() => ChangeColor(Refs[ii]))" 
               @ref="Refs[ii]"
               value="@ItemsList[ii]">
    }
    
    @code 
    {
        [Inject]
        IJSRuntime JSRuntime  { get; set; }
    
        async Task ChangeColor(ElementReference el)
        {
            await JSRuntime.InvokeVoidAsync("changeColor", el);
        }
    
        // Property that will hold the refs 
        ElementReference[] Refs { get; set; }
    
        string[] ItemsList { get; set; } = new string[]
            {
                "hey",
                "hope",
                "this",
                "works"
            };
    }