I am currently learning C# Blazor framework and I am faced with question, how to get HTML element I clicked on?
I need it to get it's position in DOM and in parent HTML element.
For example, classic way with JQuery:
$('selector').click(function (event) {
alert($(this).index());
});
http://jsfiddle.net/bCTAh/
I know, that there is @onclick attribute in Blazor, for example:
<tr @onclick="OnYes">...</tr>
@functions {
ElementReference inputTypeFileElement;
public async Task MainTableOnClick(MouseEventArgs e)
{
Console.WriteLine("clicked!");
}
}
How can I get index of TR HTML element that was clicked on?
My task is convert Windows Form app to Web-version. The old Windows Form has DataGridView, each row of that has onClick event and Tag Object too. When some of row of the DataGridView clicked, onClick get's Tag Object of the row and used it to fill data to another DataGridView's on the form. So, I need to know, what row clicked to get data from some object (it can be DataTable, or, to be more simply, Array). Based on index of row and index in Array, I need to get data for filling another tables on Web Page.
So, first table is Clients (name, surname, etc...).
When some of row with Client has been clicked, I need to get row (Client) index in the table. By that index I'll get data from Array of Clients. By found Client object I plan to fill another tables on the page dynamically.
In this case, you can use JSInterop
Or
<tr @onclick="() => TrClickedAtIndex(0)">...</tr>
@code {
ElementReference inputTypeFileElement;
public void TrClickedAtIndex(int index)
{
Console.WriteLine($"tr clicked at index {index}!");
}
}
If you want to get the element you can use a @ref
to return an element, but generally in Blazor you're not interest in the elements (as you might in JQuery) but what they relate to.
I created this simple BlazorFiddle that lists three strings in a table. It's similar to the other answer but it demonstrates a little wrinkle - when passing a value from a loop or enumeration you need to assign it.
https://blazorfiddle.com/s/br8lwsl2
This shows a table for three strings. When you click a row, it passes the data item from the clicked row - not just an index.
int index = i;
<tr @onclick="()=> ClickedRow(list[index])" ><td>
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With