Alpine.js: Dynamically Add and Remove Form Fields
1 min readNov 24, 2024
Add and Remove Form Fields
create index.html with alpinejs and bootstrap css.
reference: alpinejs, bootstrap
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alpine JS</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body class="container py-3">
<form method="post">
<div x-data="{ items: [] }">
<template x-for="(item, index) in items" x-bind:key="item">
<div class="input-group mb-2" x-data="{ placeholder: 'Enter data for index '+String(index) , name: 'id-'+String(index) }">
<input type="text" class="form-control" x-bind:placeholder="placeholder" x-bind:name="name">
<span class="input-group-text" x-on:click="items.splice(index, 1)">Remove</span>
</div>
</template>
<button type="button" class="btn btn-secondary mb-3" x-on:click="items.push(Date.now())">Add form field</button>
</div>
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/alpinejs" defer></script>
</body>
</html>
The x-data
directive is used to define a piece of reactive state within an HTML element.
The x-for
directive is used to iterate over an array and render a template for each item. It's similar to a for
loop in traditional JavaScript.
The x-bind
directive, often shortened to :
, is used to dynamically bind attributes to data.
The x-on:click
provides a clean and concise way to handle click events.