helios
helios

Reputation: 13

Fetching values from database and showing it in a form upon button click in Laravel

We have a table whose contents are fetched from database. Now, we want to fill a form by data of the relevant row of table that was clicked in Laravel.

This is how the table (left) and the form looks

Table code:

<table id="category_table" class="table table-bordered table-hover">
                  <thead>
                  </thead>
                  <tbody>
                  @foreach($cat as $c)    
                  <tr>
                  <?php $index=1;?>
                    <td>{{$c->cat_name}}</td>
                    <td width="5%"><button class="btn btn-info" onclick=fill(this)><i class="fa fa-arrow-right"></i></button>
                  </tr>
                  <?php $index=$index+1;?>
                  @endforeach
                  </tbody>
                  <tfoot>
                  </tfoot>
                </table>

This is a part of form code:

 <div class="card-body">
                  <div class="form-group">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" placeholder="Enter Name" value="">
                  </div>
                  <div class="form-group">
                    <label for="short_name">Short Name</label>
                    <input type="text" class="form-control" id="short_name" placeholder="Short Name">
                  </div>
                  <div class="form-group">
                    <label for="description">Description</label>
                    <textarea class="form-control" id="description" placeholder="Description"></textarea>
                  </div>

This is the javascript part that fetched the selected table row value through which we need to fetch other values from the database into form:

<script type="text/javascript">  
      function fill(e)
      {  
        var $item = $(e).closest("tr").find("td:first").text();  
        document.getElementById("name").value= $item;    
        }
      }  
    </script> 

Upvotes: 1

Views: 478

Answers (1)

wschopohl
wschopohl

Reputation: 1732

You can do something like this:

<button class="btn btn-info" data-model='{{$c->toJson()}}' onclick="fill()">

// then in js something like
function fill() {
    let $item = $(this).attr("data-model");
    console.log($item); // item should have all the data
}

Edit:

The questioner didn't make use of Laravel Eloquent Models. That's why the solution, in this case, deals with normal php objects like so:

data-model='{{ json_encode($c)}}'

Upvotes: 1

Related Questions