首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Jquery验证多行中的一行。

Jquery验证多行中的一行。
EN

Stack Overflow用户
提问于 2022-12-01 10:26:01
回答 2查看 39关注 0票数 0

我在一个清单项目中工作,我使用引导模式插入和更新记录。我面临的问题是,当我编辑记录时,jquery验证只应用于第一行,而不是在任何其他行上,任何人都可以在这方面帮助我。

索引页类似于下面

代码语言:javascript
运行
复制
<tbody>
  @foreach ($suppliers as $key => $supplier)
    <tr class="odd">
      <td class="sorting_1 dtr-control">{{ $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" class="fas fa-edit"                                                 title="Edit Data" style=" margin-right:20px">
         </a>
      @include('backend.supplier.editSupplier')
   </td>
    </tr>
  @endforeach
</tbody>

模式类似于下面

代码语言:javascript
运行
复制
<div class="modal fade editModal" id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
      aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
          <div class="modal-content">
              <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Edit Supplier</h5>
                  <button type="button" class=" btn btn-danger btn btn-sm close" 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) }}"
                  class="needs-validation" novalidate>
                  @csrf
                  @method('PUT')
                  <div class="modal-body">
                      <!-- name -->
                      <div class="col-md-12 ">
                          <div class="mb-3 position-relative form-group">
                               <input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name"
                                  id="name" name="name1" value="{{ $supplier->name }}">
                          </div>
                      </div>
                      <!-- mobile number -->
                      <div class="col-md-12 ">
                          <div class="mb-3 position-relative form-group">
                              <input class="form-control " type="text" autocomplete="mobile_no"
                                  placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
                                  value="{{ $supplier->mobile_no }}">

                          </div>
                      </div>
                      <!-- email -->
                      <div class="col-md-12 ">
                          <div class="mb-3 position-relative form-group">
                              <input class="form-control " type="email_address" placeholder="Email" id="email_address"
                                  name="email_address1" value="{{ $supplier->email }}">
                          </div>
                      </div>
                      <div class="col-md-12 ">
                          <div class="mb-3 position-relative form-group">
                              <input class="form-control" type="text" autocomplete="address" placeholder="Address"
                                  id="address" name="address1" value="{{ $supplier->address }}">
                          </div>
                      </div>
                  </div>
                  <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
                          onclick="resetForm()">No</button>
                      <button type="submit" class="btn btn-primary">Add Supplier</button>
                  </div>
              </form>
          </div>
      </div>
  </div>

Jquery代码类似于下面的代码

代码语言:javascript
运行
复制
<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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-12-01 20:53:20

这是一个非常冗长的例子,但是这里我使用一个呈现的表并从其中删除表单。这避免了表单上id的重复,还提供了更小的HTML和在每一行和每一行上使用相同表单以及“添加”操作的能力。

然后,我使用编辑链接/按钮触发编辑;它通过提交表单进行保存,但是您可以修改它,以便使用ajax或其他方式发布数据。

我没有冒险进入"add“,但您也可以在屏幕上添加一个按钮;在"action”中插入id或任何您需要的东西,以保存该部分中的新项目。

代码语言:javascript
运行
复制
$(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();
}
代码语言:javascript
运行
复制
.edit-link {
  margin-right: 20px;
}

.edit-modal-container {}

.cheers {
  border: solid 1px green;
}
代码语言:javascript
运行
复制
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/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/bootstrap@5.2.3/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" class="my-great-suppliers-container">
  <tbody>
    <tr class="supplier-row odd">
      <td class="sorting_1 dtr-control">$key1</td>
      <td class='edit-me' data-suppliername="Dirt supplier">Dirt supplier</td>
      <td class="edit-me" data-mobile="123-123-1234">123-123-1234</td>
      <td class="edit-me" data-email="happydays@example.com">happydays@example.com</td>
      <td class="edit-me" data-address="1234 Main St">1234 Main St</td>
      <td>
        <a href="#" data-supplierid="supplier-1" data-bs-toggle="modal" class="edit-link fas fa-edit" title="Edit Data" data-bs-target="#supplier-modal">
        </a>
      </td>
    </tr>
    <tr class="supplier-row odd">
      <td class="sorting_1 dtr-control">$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="biggerrocks@example.com">biggerrocks@example.com</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" class="edit-link fas fa-edit" data-bs-target="#supplier-modal" title="Edit Data">
        </a>
      </td>
    </tr>
  </tbody>
</table>
<div id="edit-modal-container" class="edit-modal-container">
  <div id='supplier-modal' class="edit-modal-child modal fade editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Edit Supplier</h5>
          <button type="button" class="btn btn-danger btn btn-sm close" data-bs-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                  </button>
        </div>
        <form id="editForm" method="POST" action="/route/supplierupdate/" class="needs-validation" novalidate>
          <div class="modal-body">
            <div class="col-md-12 ">
              <div class="mb-3 position-relative form-group">
                <input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name" id="name" name="name1" value="">
              </div>
            </div>
            <div class="col-md-12 ">
              <div class="mb-3 position-relative form-group">
                <input class="form-control " type="text" autocomplete="mobile_no" placeholder="Mobile Number" id="mobile_no" name="mobile_no1" value="">
              </div>
            </div>
            <div class="col-md-12 ">
              <div class="mb-3 position-relative form-group">
                <input class="form-control " type="email_address" placeholder="Email" id="email_address" name="email_address1" value="">
              </div>
            </div>
            <div class="col-md-12 ">
              <div class="mb-3 position-relative form-group">
                <input class="form-control" type="text" autocomplete="address" placeholder="Address" id="address" name="address1" value="">
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="resetForm()">No</button>
            <button type="submit" class="submit-button btn btn-primary">Add Supplier</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

票数 1
EN

Stack Overflow用户

发布于 2022-12-01 17:55:17

如果您试图检查每一行的模态。输入将具有相同的名称例如。name1、mobile_no1等。

Jquery将使用该名称验证第一个输入元素。

  1. ,您可以移动模式和Jquery函数,每个函数都有自己独特的id。可使用$

->id

  1. ,我猜这个模式已经在前驱里面了,因为它有唯一的id。更新eqch输入以包含唯一id(name="mobile_no1<?php $supplier-id ?>"),然后更新jquery函数以接受id标识符($supplier>id),以便它能够获取唯一的输入元素

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74640372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档