phplaravellaravel-livewirealpine.jslaravel-livewire-wiremodel

Livewire model binding while clicking other element


I have a very simple problem. Whenever I click on div I want the data binding to be applied to the file input.

<div>click me</div>
<input type="file" wire:model="photo"> <!-- while clicking on div, it should do the data binding to this file input  -->

I have been searching for it in the documentation but couldn't find any clue. Is it possible to do that?


Solution

  • Okei i was searching and testing, to see if i can acomplish that, and there is a solution with jquery:

    <div id="trigger">click me</div>
    <input type="file" id="file_input" wire:model="photo">
    
    $("#trigger").unbind("click").bind("click", function () {
        $("#file_input").click();
    });
    

    i will give credit where i found the answer:

    triggering a file input button

    if your idea is to use livewire only, you could create a function

    public function fileTrigger(){
        $this->dispatchBrowserEvent('TriggerFilem');
    }
    

    add this to js:

    window.addEventListener('TriggerFilem', e => {
        $("#trigger").unbind("click").bind("click", function () {
            $("#file_input").click();
    });
    }); 
    

    and in the view:

    <div wire:click="fileTrigger()" id="trigger">click me</div>
    <input type="file" id="file_input" wire:model="photo">
    

    Edit:

    If you don't want to use jquery, i was testing a solution on js only:

    document.getElementById('trigger').addEventListener("click",() => {
        document.getElementById('file_input').click();
        
        });
    

    hope it helps!