Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add and Remove dom elements using alpine JS

Tags:

alpine.js

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);
        }
    }
like image 298
Kingsley Uchenna Avatar asked Jun 13 '26 02:06

Kingsley Uchenna


2 Answers

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);
        }
    }
}
like image 51
Kingsley Uchenna Avatar answered Jun 18 '26 00:06

Kingsley Uchenna


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

like image 33
Yusuf Abid Avatar answered Jun 17 '26 23:06

Yusuf Abid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!