Search code examples
javascriptlaravellaravel-livewire

Get value from JavaScript to Livewire Component


Could you tell me if it is possible to get the value of a JavaScript field and pass it to a Laravel Livewire property:

First I load in an input with JavaScript the following value:

document.getElementById('lat-span').value = (place.geometry['location'].lat());

This loads the input with the value, now I tried to retrieve that value with wire: model and it appears null, I understand that it is not done the way I had in mind:

<input  wire:model="latitud" value="lat-span" id="lat-span" />

How can I directly pass this JavaScript value to Livewire property?


Solution

  • <script>
    // ....
    Livewire.emit('getLatitudeForInput', place.geometry['location'].lat());
    </script>
    

    In component:

    public $latitud;
    protected $listeners = [
         'getLatitudeForInput'
    ];
    //
    public function getLatitudeForInput($value)
    {
        if(!is_null($value))
            $this->latitud = $value;
    }
    

    In Blade just:

    <input  wire:model="latitud" id="lat-span" />