Laravel 7 - Dynamically Add Input Fields using HandlebarsJs

  260 views   4 months ago Laravel

Hello Artisan

In this tutorial i will discuss about dynamically integrate multiple input fields and submit to database with jquery and laravel. We can optically discern addremove multiple input fields dynamically with jquery laravel from scratch so that we can understand facilely.

You can utilize jQuery only to do laravel integrate more fields example in your application. But in this example i will utilize handlebars js as well as jQuery to engender laravel dynamic form fields validation example.

I additionally validate form and then preserve it into database. Sometimes we require it in our application like gregarious list field or task list etc. That situation we can engender this integrate dynamically more then one fields with laravel jQuery and handlebars js. 

Simply in this example tutorial i will utilize a Task model to preserve form data that contains two filed. one is task_name and other is cost. Then we preserve it into database. Visually perceive the preview of this tutorial.

Task From

Step 1 : Install Laravel Application

I am going to show you from scratch, So we require to get fresh current Laravel 7.x  version application using bellow command, So open your terminal and run

composer create-project --prefer-dist laravel/laravel blog

Step 2: Create Task Table and Model

We are going to create add more dynamic field application for task list. So we have to create migration for task list table using Laravel 7.x  php artisan command, so first fire bellow command

php artisan make:model Task -m

database/migrations/create_task_table

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('task_name');
            $table->integer('cost');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schem

As we have to save add more input field data in our database to we need to setup our Task model.

app/Task.php


namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $guarded = [];

}

Step 3: Create Routes

In this is step we need to add two route for add more fields example. so open your routes/web.php file and add following route. As this is a example tutorial so i won't use any controller. I simply do it from web.php file.

routes/web.php

use App\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
})->name('task');

Route::post('/',function(Request $request) {
    
    $request->validate([
       'task_name' => 'required',
       'cost' => 'required'
    ]);
    
    $count = count($request->task_name);

    for ($i=0; $i < $count; $i++) { 
	  $task = new Task();
	  $task->task_name = $request->task_name[$i];
	  $task->cost = $request->cost[$i];
	  $task->save();
    }

    return redirect()->back();
});

Step 4: Create Blade File

Now we need to show our add more field form in our welcome blade file. In this step we have to create just welcome.blade.php blade file.

So let's just create following file and put bellow code.

resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>{{ config('app.name') }}</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    </head>
<body>

   <div class="container" style="margin-top:200px;">
      <div class="row">
        <div class="col-md-2">
            <label for="">Enter Task</label>
            <input type="text" placeholder="Enter task" class="form-control form-control-sm" name="task_name"  id="task_name" value="">
            <font style="color:red"> {{ $errors->has('task_name') ?  $errors->first('task_name') : '' }} </font>
        </div>
        <div class="col-md-2">
            <label for="">Enter Cost</label>
            <input type="number" placeholder="Enter task" class="form-control form-control-sm" name="cost"  id="cost" value="">
            <font style="color:red"> {{ $errors->has('cost') ?  $errors->first('cost') : '' }} </font>
        </div>
        <div class="col-md-2" style="margin-top:26px;">
            <button id="addMore" class="btn btn-success btn-sm">Add More </button>
        </div>
     </div>
     <div class="row" style="margin-top:26px;">
    <div class="col-md-5">


  <form action="{{ route('task') }}" method="post">
    @csrf
    
    <table class="table table-sm table-bordered" style="display: none;">
    <thead>
        <tr>
            <th>Name</th>
            <th>Cost</th>
            <th>Action</th>
        </tr>
    </thead>

    <tbody id="addRow" class="addRow">

    </tbody>
    <tbody>
      <tr>
        <td colspan="1" class="text-right">
            <strong>Total:</strong> 
        </td>
        <td>
            <input type="number" id="estimated_ammount" class="estimated_ammount" value="0" readonly>
        </td>
      </tr>
    </tbody>

    </table>
   <button type="submit" class="btn btn-success btn-sm">Submit</button>
  </form>

    </div>
  </div>
</div>


<script src="//code.jquery.com/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.min.js"></script> 

<script id="document-template" type="text/x-handlebars-template">
  <tr class="delete_add_more_item" id="delete_add_more_item">

      <td>
        <input type="text" name="task_name[]" value="@{{ task_name }}">
      </td>
      <td>
        <input type="number" class="cost" name="cost[]" value="@{{ cost }}">
      </td>
  
      <td>
       <i class="removeaddmore" style="cursor:pointer;color:red;">Remove</i>
      </td>

  </tr>
 </script>

<script type="text/javascript">
 
 $(document).on('click','#addMore',function(){
    
     $('.table').show();

     var task_name = $("#task_name").val();
     var cost = $("#cost").val();
     var source = $("#document-template").html();
     var template = Handlebars.compile(source);

     var data = {
        task_name: task_name,
        cost: cost
     }

     var html = template(data);
     $("#addRow").append(html)
   
     total_ammount_price();
 });

  $(document).on('click','.removeaddmore',function(event){
    $(this).closest('.delete_add_more_item').remove();
    total_ammount_price();
  });

  function total_ammount_price() {
    var sum = 0;
    $('.cost').each(function(){
      var value = $(this).val();
      if(value.length != 0)
      {
        sum += parseFloat(value);
      }
    });
    $('#estimated_ammount').val(sum);
  }
                       
</script>

    </body>
</html> 

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles