Why we need to use AlpineJS, a simple answer is to that is create a better experience. Over the years, we use jQuery to create an event listener on the button clicks, form submits, or other manipulations on the web page. It works perfectly for our requirements, but an imperative method ( asking the browser to what exactly need to be done) gets messy over the time.
When we have more code, it will create spaghetti of code. Because it’s all the instructions that we write to execute in browser.
So engineers on the internet invented solutions like Vuejs, Reactjs, Angualrjs, cleaner code, using virtual DOM. Instead of using CSS properties, it manipulates the virtual DOM itself. For example, normally hiding a tab we use
display:none
in CSS(or jQuery). But in above solutions performs a complete removal of virtual DOM and allows declarative code.All these above solutions relies on manipulation of virtual DOM, but Alpinejs is a light weight alternate for this with a total weight of 6kb.
Today’s article we will show how to add dynamic form fields using AlpineJS.
HTML
<div class="container"> <h1 class="text-center fs-4">Alpinejs Add More </h1> <div class="row" x-data="handler()"> <div class="col"> <table class="table table-bordered align-items-center table-sm"> <thead class="thead-light"> <tr> <th>#</th> <th>Name</th> <th>email</th> <th>Delete</th> </tr> </thead> <tbody> <template x-for="(field, index) in fields" :key="index"> <tr> <td x-text="index + 1"></td> <td><input x-model="field.name" type="text" name="name[]" class="form-control"></td> <td><input x-model="field.email" type="text" name="email[]" class="form-control"></td> <td> <button type="button" class="btn btn-danger btn-small" @click="removeField(index)">×</button> <button type="button" class="btn btn-primary" @click="saveForm(index)">Save</button> </td> </tr> </template> </tbody> <tfoot> <tr> <td colspan="4" class="text-right"><button type="button" class="btn btn-info" @click="addNewField()">+ Add Row</button></td> </tr> </tfoot> </table> </div> </div> </div>
Javascript
<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.js" type="text/javascript"></script> <script type="text/javascript"> function handler() { return { fields: [], addNewField() { this.fields.push({ name: '', email: '' }); }, removeField(index) { this.fields.splice(index, 1); }, saveForm(index) { alert(index); console.log(this.fields[index]); //You can process your form using fetch() or axios let web_api = '/contact'; let response = fetch(web_api, { method: "POST", body: JSON.stringify(this.fields[index]), headers: { "Content-Type": "application/json", }, }).then((response) => { if (!response.ok) { throw new Error("There was an error processing the request"); } }); } } } </script>