• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsAlpineJS

Add dynamic form fields using AlpineJS

May 27, 2021 Editorial Staff

Share
Tweet
Share
1 Shares
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)">&times;</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>
 

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required

Search Here

Share

   

Hot topics

  • Replace “\n” with new line characters, using Notepad++ 57 views
  • How to enter new line in Microsoft Teams? 38 views
  • Open a URL in a new tab using JavaScript 28 views
  • A Simple YouTube Video Downloader Script in PHP 23 views
  • Laravel WhereHas() Eloquent Example 19 views
  • How to Create PDF File From HTML Form Using Fpdf? 18 views
  • How to change PHP version on MAMP – Mac OSX 18 views
  • PHP: Implode () with quotes 15 views
  • Simple PHP Shopping Cart 15 views
  • Get Uploads Directory Path in WordPress 14 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube

Copyright © 2022 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com