7

I am trying to build a custom add and remove entire div element from an array using alpine JS, here is my code which is working but instead of removing from the exact remove button click it will remove the last one on the array.

HTML

<div x-data="addRemove()">
  <template x-for="(field, index) in fields" :key="index">
    <div>
      <input type="text" name="txt1[]" class="form-input">
      <button type="button" class="btn btn-danger btn-small" @click="removeField(index)">&times;</button>
    </div>
  </template>
  <button type="button" @click="addNewField()">+ Add Row</button>
</div>

JAVASCRIPT

return {
        fields: [],
        addNewField() {
            this.fields.push({});
        },
        removeField(index) {
            this.fields.splice(index, 1);
        }
    }
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Kingsley Uchenna
  • 580
  • 3
  • 15

2 Answers2

7

Found a solution, this is what I did.

HTML

<div x-data="addRemove()">
  <template x-for="(field, index) in fields" :key="field.id">
    <div>
      <input type="text" name="txt1[]" class="form-input">
      <button type="button" class="btn btn-danger btn-small" @click="removeField(field)">&times;</button>
    </div>
  </template>
  <button type="button" @click="addNewField()">+ Add Row</button>
</div>

JAVASCRIPT

function addRemove() {
    return {
        fields: [],
        addNewField() {
            this.fields.push({id: new Date().getTime() + this.fields.length});
        },
        removeField(field) {
            this.fields.splice(this.fields.indexOf(field), 1);
        }
    }
}
Kingsley Uchenna
  • 580
  • 3
  • 15
4

You've to set the 'key' with a unique value in the looping.

<div x-data="{data: []}">
    <div @click="data.push({ randomNumber: new Date().getTime()})">(Click Here To Add New Data)</div>
    <template x-for="(item, index) in data" :key="index">
        <div>
            <span x-text="item.randomNumber"></span>
            <span @click="data.splice(index, 1)">Remove</span>
        </div>
    </template>
</div>

online test: https://codepen.io/yuxufm/pen/YzLoxvE

Yusuf Abid
  • 59
  • 3