Skip to content
Advertisement

How to force the second, third… and next rows to show Delete Button in dynamic field in Laravel?

When I fetch data in from datatabse to dynamic form it shows like this. How to force the second, third… and next rows to show DELETE button. I want the first row only to show Add and the rest is delete.
enter image description here

My blade code

@foreach ($form->requirements as $reqs)
      <tr>
          <td><input type="text" name="addMoreInputFields[0][requirement]"
                 placeholder="Enter requirements"
              value="{{ $reqs['requirement'] }}"class="form-control" />
          </td>
          <td><button type="button" name="add" id="dynamic-ar"
                class="btn btn-outline-primary">Add</button>
          </td>
     </tr>
 @endforeach

the script

var i = 0;
$("#dynamic-ar").click(function() {
  ++i;
  $("#dynamicAddRemove").append('<tr><td><input type="text" name="addMoreInputFields[' + i +
    '][requirement]" placeholder="Enter requirements" class="form-control" /></td><td><button type="button" class="btn btn-outline-danger remove-input-field">Delete</button></td></tr>'
  );
});
$(document).on('click', '.remove-input-field', function() {
  $(this).parents('tr').remove();
});

Advertisement

Answer

You can use the $loop variable made available to you by Laravel:

@foreach ($form->requirements as $reqs)
      <tr>
          <td><input type="text" name="addMoreInputFields[0][requirement]"
                 placeholder="Enter requirements"
              value="{{ $reqs['requirement'] }}"class="form-control" />
          </td>
          <td><button type="button" name="add" id="dynamic-ar"
                class="btn btn-outline-primary">Add</button>
          </td>
          @if (!$loop->first)
            // your delete button code here
          @endif
     </tr>
 @endforeach
Advertisement