简体   繁体   中英

How can i sum 2 input values using laravel-livewire

i want to sum 2 values.

my livewire blade codes:

<label>Sayı 1:</label>
<input type="text" id="a" name="a" wire:model.lazy="a">
<br>

<label>Sayı 2:</label>
<input type="text" id="b" name="b" wire:model.lazy="b">
<br>
Sonuç : {{ $result}}

in livewire file

public $result;
public $a;
public $b;

public function render()
{   
   $this->result=$this->a+$this->b;
    return view('livewire.try1');
}

i can not see the result on my page.

i have changed $this->result=$this->a+$this->b; line to $this->result=a+b; and it shows that undefined variable $a .

i have opened debugbar a and b is null.

so i could not make it work.

First and foremost, your Livewire views should always be wrapped in a single div, kind of like this,

<div>
    <label>Sayı 1:</label>
    <input type="text" id="a" name="a" wire:model.lazy="a">

    <br>
    <label>Sayı 2:</label>
    <input type="text" id="b" name="b" wire:model.lazy="b">
    
    <br>
    Sonuç : {{ $result }}
</div>

Then I would suggest that you use a lifecycle-hook for updated to maintain the result,

public $result;
public $a;
public $b;

public function updated()
{
    $this->result = ($this->a ?? 0) + ($this->b ?? 0);
}

public function render()
{
    return view('livewire.try1');
}

Also, since you have the lazy modifier on your binding, beware that it will not update until you click away from the input, see https://laravel-livewire.com/docs/2.x/properties#lazy-updating

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM