Home > Software design >  Jquery validates one row out of many rows
Jquery validates one row out of many rows

Time:12-02

I am working in one inventory project I use bootsrap modal for inserting and updating records the problem that I am facing is that when I am editing the record the jquery validation only applied on first row not on any other row can any one help me in this matter.

index page is like below

<tbody>
  @foreach ($suppliers as $key => $supplier)
    <tr >
      <td >{{ $key   1 }}</td>
      <td>{{ $supplier->name }}</td>
      <td>{{ $supplier->mobile_no }}</td>
      <td>{{ $supplier->email }}</td>
      <td>{{ $supplier->address }}</td>
      <td>
          <a href="#edit{{ $supplier->id }}" data-bs-toggle="modal"                                                  title="Edit Data" style=" margin-right:20px">
         </a>
      @include('backend.supplier.editSupplier')
   </td>
    </tr>
  @endforeach
</tbody>

Modal is like below

<div  id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
      aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div  role="document">
          <div >
              <div >
                  <h5  id="exampleModalLabel">Edit Supplier</h5>
                  <button type="button"  data-bs-dismiss="modal"
                      aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
              </div>
              <form id="editForm" method="POST" action="{{ route('supplier.update', $supplier->id) }}"
                   novalidate>
                  @csrf
                  @method('PUT')
                  <div >
                      <!-- name -->
                      <div >
                          <div >
                               <input  type="text" autocomplete="name" placeholder="Supplier Name"
                                  id="name" name="name1" value="{{ $supplier->name }}">
                          </div>
                      </div>
                      <!-- mobile number -->
                      <div >
                          <div >
                              <input  type="text" autocomplete="mobile_no"
                                  placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
                                  value="{{ $supplier->mobile_no }}">

                          </div>
                      </div>
                      <!-- email -->
                      <div >
                          <div >
                              <input  type="email_address" placeholder="Email" id="email_address"
                                  name="email_address1" value="{{ $supplier->email }}">
                          </div>
                      </div>
                      <div >
                          <div >
                              <input  type="text" autocomplete="address" placeholder="Address"
                                  id="address" name="address1" value="{{ $supplier->address }}">
                          </div>
                      </div>
                  </div>
                  <div >
                      <button type="button"  data-bs-dismiss="modal"
                          onclick="resetForm()">No</button>
                      <button type="submit" >Add Supplier</button>
                  </div>
              </form>
          </div>
      </div>
  </div>

Jquery code is like below

<script type="text/javascript">
        $(document).ready(function() {
            $('#editForm').validate({
                rules: {
                    name1: {
                        required: true,
                    },
                    mobile_no1: {
                        required: true,
                    },
                    address1: {
                        required: true,
                    },
                    email_address1: {
                        required: true,
                    },
                },
                messages: {
                    name1: {
                        required: 'Please Enter Supplier Name',
                    },
                    mobile_no1: {
                        required: 'Please Enter Supplier mobile number',
                    },
                    address1: {
                        required: 'Please Enter Supplier address',
                    },
                    email_address1: {
                        required: 'Please Enter Supplier email',
                    },
                },
                errorElement: 'span',
                errorPlacement: function(error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function(element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function(element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                },
            });

        });
     
      function resetForm() {
          $("#editForm").trigger("reset");

          var validator = $("#editForm").validate();
          validator.resetForm();
      }
  </script>

CodePudding user response:

if you try to inspect the modal on each row. the input will have the same name eg. name1, mobile_no1, etc.

Jquery will validate the first input element with that name.

  1. You can either move the modal and Jquery function each with their own unique id inside foreach. may use $supplier->id

Or

  1. Im guessing the modal already inside the foreach since it have the unique id. Update eqch input to include the unique id(name="mobile_no1<?php $supplier-id ?>") Then, update the jquery function to accept id identifier($supplier->id) so it can fetch the unique input element

CodePudding user response:

This is a VERY verbose example but here I take a rendered table and remove the form from that. This avoids duplication of the id's on the form and also gives you smaller HTML and the ability to use the same form over in every row and on and "add" action.

I then trigger the edit with the edit link/button; it saves by submit of the form but you could alter that to post the data using ajax or something also.

I did not venture into the "add" but you could put a button on the screen for that also; stick the id or whatever you need in the "action" to save the NEW item in that part.

$(function() {
  $('#editForm').validate({
    rules: {
      name1: {
        required: true,
      },
      mobile_no1: {
        required: true,
      },
      address1: {
        required: true,
      },
      email_address1: {
        required: true,
      }
    },
    messages: {
      name1: {
        required: 'Please Enter Supplier Name',
      },
      mobile_no1: {
        required: 'Please Enter Supplier mobile number',
      },
      address1: {
        required: 'Please Enter Supplier address',
      },
      email_address1: {
        required: 'Please Enter Supplier email',
      }
    },
    errorElement: 'span',
    errorPlacement: function(error, element) {
      error.addClass('invalid-feedback');
      element.closest('.form-group').append(error);
    },
    highlight: function(element, errorClass, validClass) {
      $(element).addClass('is-invalid');
    },
    unhighlight: function(element, errorClass, validClass) {
      $(element).removeClass('is-invalid');
    }
  });

  $('#my-great-suppliers').on('click', '.edit-link', function(event) {
    //event.preventDefault().preventPropagation();
    console.log('set up edit');
    const trow = $(this).closest('.supplier-row');
    console.log("Row:", trow.index(), trow.length);
    const modal = $('#edit-modal-container').find('.edit-modal-child');
    const modalForm = modal.find('#editForm');
    const rowEdits = trow.find('.edit-me');
    let supplierid = $(this).data("supplierid");
    let name = rowEdits.filter('[data-suppliername]').data("suppliername");
    let email = rowEdits.filter('[data-email]').data("email");
    let mobile = rowEdits.filter('[data-mobile]').data("mobile");
    let address = rowEdits.filter('[data-address]').data("address");
    console.log(supplierid, name, trow.length);
    modalForm.find('#name').val(name);
    modalForm.find('#email_address').val(email);
    modalForm.find('#address').val(address);
    modalForm.find('#mobile_no').val(mobile);
    let actionV = modalForm.attr("action");
    console.log(actionV);
    // update the form action with the id
    modalForm.attr("action", actionV   supplierid);
    //  modal.show();
  });
  $('.submit-button').on('click', function(event) {
    event.preventDefault();
    const modalForm = $('#editForm');
    console.log("trying to save");
    // now do what you need to validate
    if (modalForm.valid()) {
      // add your extra logic here to execute only when element is valid
      console.log('It is valid');
      let savedata = {
        name: modalForm.find('#name').val(),
        email: modalForm.find('#email_address').val(),
        address: modalForm.find('#address').val(),
        mobile: modalForm.find('#mobile_no').val()
      };
      console.log("Saving:", savedata, 'To:', modalForm.attr("action"));
      //now do what you want to save the form
      // since we updated the action when edit started we have the id in there
      //  modalForm.submit()
    }
  });
});

function resetForm() {
  $("#editForm").trigger("reset");
  let validator = $("#editForm").validate();
  validator.resetForm();
}
.edit-link {
  margin-right: 20px;
}

.edit-modal-container {}

.cheers {
  border: solid 1px green;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8 y gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL jjXkk Q2h455rYXK/7HAuoJl 0I4" crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<table id="my-great-suppliers" >
  <tbody>
    <tr >
      <td >$key1</td>
      <td class='edit-me' data-suppliername="Dirt supplier">Dirt supplier</td>
      <td  data-mobile="123-123-1234">123-123-1234</td>
      <td  data-email="[email protected]">[email protected]</td>
      <td  data-address="1234 Main St">1234 Main St</td>
      <td>
        <a href="#" data-supplierid="supplier-1" data-bs-toggle="modal"  title="Edit Data" data-bs-target="#supplier-modal">
        </a>
      </td>
    </tr>
    <tr >
      <td >$key2</td>
      <td class='edit-me' data-suppliername="Rock supplier">Rock supplier</td>
      <td class='edit-me' data-mobile="321-123-4321">321-123-4321</td>
      <td class='edit-me' data-email="[email protected]">[email protected]</td>
      <td class='edit-me' data-address="12 Granite Lane">12 Granite Lane</td>
      <td>
        <a href="#" data-supplierid="supplier-2" data-bs-toggle="modal"  data-bs-target="#supplier-modal" title="Edit Data">
        </a>
      </td>
    </tr>
  </tbody>
</table>
<div id="edit-modal-container" >
  <div id='supplier-modal'  tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div  role="document">
      <div >
        <div >
          <h5 >Edit Supplier</h5>
          <button type="button"  data-bs-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
        </div>
        <form id="editForm" method="POST" action="/route/supplierupdate/"  novalidate>
          <div >
            <div >
              <div >
                <input  type="text" autocomplete="name" placeholder="Supplier Name" id="name" name="name1" value="">
              </div>
            </div>
            <div >
              <div >
                <input  type="text" autocomplete="mobile_no" placeholder="Mobile Number" id="mobile_no" name="mobile_no1" value="">
              </div>
            </div>
            <div >
              <div >
                <input  type="email_address" placeholder="Email" id="email_address" name="email_address1" value="">
              </div>
            </div>
            <div >
              <div >
                <input  type="text" autocomplete="address" placeholder="Address" id="address" name="address1" value="">
              </div>
            </div>
          </div>
          <div >
            <button type="button"  data-bs-dismiss="modal" onclick="resetForm()">No</button>
            <button type="submit" >Add Supplier</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

  • Related