zxtanzxzx
1 month ago
101
1
General

Input field dissappear when click livewire action

Posted 1 month ago by zxtanzxzx

I am trying to create a dynamic form using livewire that allow user to add more members When i click the "Add Member" button, the event trigger and new member fields was added. However, when the second new member fields added, the existing first field will somehow dissappear.

Look at the screenshot here: https://imgur.com/a/YO9PlwQ

Livewire member.blade

<div>
    {{-- First Member --}}
    <div>
        <div>
            <button class="btn btn-danger btn-sm" wire:click.prevent="add({{$i}})">Add Member</button>
        </div>
        <div>
            <div>
                <label for="memberType">Member Type</label>
                <select name="memberType" id="memberType">
                    <option value="0">TAR UC Student</option>
                    <option value="1">TAR UC Staff</option>
                </select>
            </div>
        </div>
    </div>

    {{-- Second and More Member --}}
    @foreach ($inputs as $key => $value)
    <br>
    <div>
        <div>
            <div>
            <button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove Member {{$key}}</button>
            </div>
        </div>
        <div>
            <label for="memberType">Member Type</label>
            <select name="memberType" id="memberType">
                <option value="0">Student</option>
                <option value="1">Staff</option>
            </select>
        </div>
    </div>
    @endforeach
</div>

Livewire member.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class Member extends Component
{
    public $member_type;

    public $member_list = [
        'member' => [],
        'index' => 0,
    ];

    public $updateMode = false;
    public $inputs = [];
    public $i = 1;

    public function add($i)
    {
        if (count($this->inputs)  < 10) {
            $i = $i + 1;
            $this->i = $i;
            array_push($this->inputs , $i);
        } 
    }

    public function remove($i)
    {
        unset($this->inputs[$i]);
    }

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

Please sign in or create an account to participate in this conversation.