Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a blazor way of simulating a click event on an html element?

I have two elements, an InputFile and a button. And I want to simulate a click on InputFile upon clicking the button. I have it working with Js now but would like to know if there's a blazor way of doing it. An example gif

and this is the current blazor code

<InputFile id="filePicker" />
<button type="button" @onclick="OpenFilePicker">or Select</button>

private async Task OpenFilePicker() => await JsRuntime.InvokeVoidAsync("clickElement");

and with this Js code I can make it work though,

clickElement = () => document.getElementById('filePicker').click();

Is there a better solution without Js dependency ?

like image 609
Zammil Avatar asked Jan 24 '26 23:01

Zammil


1 Answers

I don't think it's possible to trigger a click event from blazor without using javascript.

You can use the ref directive to get a reference to an element from blazor but you'll still need javascrit to trigger the click on the element.

<InputFile @ref="filePicker"></InputFile>
<button type="button" @onclick="() => click()">Select a file</button>

<script>
    window.triggerClick = (elt) => elt.click();
</script>
@code {
    InputFile filePicker;
    async Task click() {
        await js.InvokeAsync<object>("triggerClick", filePicker.Element);
    }
}

But since you're trying to trigger a click on an input there's a pure html way to do it using a label

<InputFile id="filePicker"></InputFile>

<label for="filePicker">
    <button type="button" style="pointer-events: none;">Select a file</button>
</label>
like image 151
J.Loscos Avatar answered Jan 29 '26 20:01

J.Loscos



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!