Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How to add dynamic input field after click add button in laravel blade file using jquery

  1. Set up your Blade view with an initial input field and an "Add" button.
  2. Use jQuery to dynamically add input fields when the "Add" button is clicked . Here's an example:

Blade View:

define input field with the name "input1[]" inside a container div
A counter (inputCounter) is initialized to keep track of dynamic input names when we click then update it

@extends('layouts.app')

@section('content')
    <div class="container">
        <form action="{{ route('your.route') }}" method="post">
            @csrf

            <div id="dynamic-inputs-container">
                <!-- Initial input field -->
                <div class="form-group">
                    <label for="input1">Input 1</label>
                    <input type="text" name="input1[]" class="form-control">
                </div>
            </div>

            <button type="button" class="btn btn-primary" id="add-input">Add Input</button>
            <button type="submit" class="btn btn-success">Submit</button>
        </form>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        // jQuery code goes here
    </script>
@endsection
Enter fullscreen mode Exit fullscreen mode

output

Image description

The Blade view extends a layout (layouts.app) and defines a form.
Inside the form, there is an initial input field with the name input1.
There is a container div (dynamic-inputs-container) where dynamically added input fields will be placed.

Two buttons are provided: "Add Input" and "Submit."
jQuery Code:

$(document).ready(function() {
    // Counter for dynamic input names
    let inputCounter = 2;

    // Event listener for "Add Input" button
    $('#add-input').click(function() {
        // Create a new input field with a unique name
        let newInput = `<div class="form-group">
                            <label for="input${inputCounter}">Input ${inputCounter}</label>
                            <input type="text" name="input${inputCounter}[]" class="form-control">
                        </div>`;

        // Append the new input field to the container
        $('#dynamic-inputs-container').append(newInput);

        // Increment the counter for the next input field
        inputCounter++;
    });
});
Enter fullscreen mode Exit fullscreen mode

output
after adding add input

Image description

The jQuery code is wrapped in $(document).ready() to ensure it runs when the document is fully loaded.
The inputCounter variable is used to keep track of the number of dynamically added input fields.
The event listener is attached to the "Add Input" button (#add-input).
When the button is clicked, a new input field is dynamically created using a template literal. The input field has a unique name (input2[], input3[], and so on).
The new input field is appended to the dynamic-inputs-container div.
The inputCounter is incremented for the next input field.
This setup allows users to dynamically add input fields by clicking the "Add Input" button. The form can be submitted with the dynamically added input fields, and you can handle the data in your Laravel controller based on the array notation used in the input names (input1[], input2[], etc.).

full code

@extends('layouts.app')

@section('content')
    <div class="container">
        <form action="{{ route('your.route') }}" method="post">
            @csrf

            <div id="dynamic-inputs-container">
                <!-- Initial input field -->
                <div class="form-group">
                    <label for="input1">Input 1</label>
                    <input type="text" name="input1[]" class="form-control">
                </div>
            </div>

            <button type="button" class="btn btn-primary" id="add-input">Add Input</button>
            <button type="submit" class="btn btn-success">Submit</button>
        </form>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        $(document).ready(function() {
            // Counter for dynamic input names
            let inputCounter = 2;

            // Event listener for "Add Input" button
            $('#add-input').click(function() {
                // Create a new input field with a unique name
                let newInput = `<div class="form-group">
                                    <label for="input${inputCounter}">Input ${inputCounter}</label>
                                    <input type="text" name="input${inputCounter}[]" class="form-control">
                                </div>`;

                // Append the new input field to the container
                $('#dynamic-inputs-container').append(newInput);

                // Increment the counter for the next input field
                inputCounter++;
            });
        });
    </script>
@endsection
Enter fullscreen mode Exit fullscreen mode

Make sure to replace 'your.route' with the actual route where you want to handle the form submission.

In this example, the JavaScript/jQuery code listens for a click on the "Add Input" button. When clicked, it dynamically creates a new input field with a unique name and appends it to the container. The input names are set to an array (input1[], input2[], etc.) to handle multiple dynamically added fields when the form is submitted.

Create Dynamic Input Using React js

## Using React JS

// DynamicInputsForm.js
import React, { useState } from 'react';

const DynamicInputsForm = () => {
    const [inputs, setInputs] = useState([{ id: 1, value: '' }]);

    const handleInputChange = (id, value) => {
        const updatedInputs = inputs.map(input =>
            input.id === id ? { ...input, value } : input
        );
        setInputs(updatedInputs);
    };

    const handleAddInput = () => {
        setInputs([...inputs, { id: inputs.length + 1, value: '' }]);
    };

    const handleSubmit = event => {
        event.preventDefault();
        // Implement your form submission logic here
        console.log('Form submitted:', inputs);
    };

    return (
        <div className="container">
            <form onSubmit={handleSubmit}>
                {inputs.map(input => (
                    <div key={input.id} className="form-group">
                        <label htmlFor={`input${input.id}`}>{`Input ${input.id}`}</label>
                        <input
                            type="text"
                            name={`input${input.id}`}
                            value={input.value}
                            onChange={e => handleInputChange(input.id, e.target.value)}
                            className="form-control"
                        />
                    </div>
                ))}
                <button type="button" className="btn btn-primary" onClick={handleAddInput}>
                    Add Input
                </button>
                <button type="submit" className="btn btn-success">
                    Submit
                </button>
            </form>
        </div>
    );
};

export default DynamicInputsForm;
Enter fullscreen mode Exit fullscreen mode

Use this component in your main application file (e.g., App.js):

// App.js
import React from 'react';
import ReactDOM from 'react-dom';
import DynamicInputsForm from './DynamicInputsForm';

const App = () => {
    return (
        <div>
            <DynamicInputsForm />
        </div>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Make sure to include the necessary dependencies in your project. If you haven't already, you can set up a new React project using create-react-app:

npx create-react-app my-react-app
cd my-react-app
Enter fullscreen mode Exit fullscreen mode

Replace the contents of src/App.js with the content from step 2.

Run your React application:

npm start
Enter fullscreen mode Exit fullscreen mode

Summary

define input field with the name "input1[]" inside a container div
A counter (inputCounter) is initialized to keep track of dynamic input names when we click then update it

Top comments (0)