Search code examples
laravellaravel-livewire

How to avoid livewire request for simple inputs calculations?


How would I avoid doing calculation for 3 inputs using Livewire and use JS instead, but still can bind the inputs and their new values with the component.

Example:

                <input id="cash-price"
                        type="text"
                       wire:model="total_cache_price"
                       class="amount-credit">

                <input id="deposit"
                       type="text"
                       wire:model="deposit"
                       class="amount-credit">

                <input id="trade-in"
                       type="text"
                       wire:model="trade_in"
                       class="amount-credit">

I can easily do a simple calculation using JS, but the properties in Livewire component would still be empty or null after submitting the form. I am trying to avoid livewire requests for every input change.

Note: I understand the deferred updating in livewire, the problem is with the property values not changing.


Solution

  • I will show you an example in alpine js + livewire way. Here I want to set value in two inputs from a selected option in select. Please note that x-ref is used in alpine to directly access DOM elements without using getElementById.

    <div x-data="{
    from_date : @entangle('from_date').defer,
    to_date : @entangle('to_date').defer,
    dateChange(){
        select = this.$refs.years;
        this.from_date = select.options[select.selectedIndex].getAttribute('data-from');
        this.to_date = select.options[select.selectedIndex].getAttribute('data-to');
    },
    resetFilters(){
        this.net_balances = false;
    }}">
    <select x-ref="years" @change="dateChange()">
        <option value="">Year</option>
        @foreach ($years as $key => $year)
        <option wire:key="{{ 'years'.$key }}" data-from="{{ $year->from_date }}" data-to="{{ $year->to_date }}" value="{{ $year->id }}">{{ $year->name }} </option>
        @endforeach
    </select>
    <div>
        <text type="date" x-model="from_date" />
    </div>
    <div >
        <text type="date" x-model="to_date" />
    </div>