动态添加Select 2,Jquery Validations不起作用

问题描述 投票:0回答:1

我正在开发一个表单,供用户将多个商品添加到购物车,并且需要验证没有任何字段留空。为此,我使用 Select2 插件Jquery Validator 以及 jQuery。然而,尽管实现了验证,表单并没有阻止用户在字段留空时提交它。

我已为字段分配了类,以对它们应用相同的验证。如果任何现有或新添加的行缺少选定的项目和空数量,验证应阻止用户提交。

<form name='CartForm' id='CartForm' method='post'>
<table class="table table-condensed table-bordered no-padding" id="myTable">    <thead>
    <tr role="row" class="bg-blue">
         <th class="tcenter" style="vertical-align:top; width:30%">Item #, UPC or Item Name</th>
         <th class="tcenter" style="vertical-align:top; width:7%">Quantity</th>
         <th class="tcenter" style="vertical-align:top; width:9%">PO Number</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="tleft">
            <select name="view_by_item[]" data-id="1" id="view_by_item1" class="form-control view_by_item" style='width: 100%'></select>
        </td>
        <td class="tcenter">
            <input type="number" name="qty[]" id="qty1" class="qty form-control" style="text-align:right;">
        </td>
        <td class="tcenter">
            <input type="text" name="ponum[]" class="ponum form-control" placeholder="Optional">
        </td>
    </tr>
    <tr>
        <td class="tleft">
            <select name="view_by_item[]" data-id="2" id="view_by_item2" class="form-control view_by_item" style='width: 100%'></select>
        </td>
        <td class="tcenter">
            <input type="number" name="qty[]" id="qty2" class="qty form-control" style="text-align:right;">
        </td>
        <td class="tcenter">
            <input type="text" name="ponum[]" class="ponum form-control" placeholder="Optional">
        </td>
    </tr>
    </tbody>
 </table>

<button type="button" class="btn btn-secondary plusbutton"> Add Item</button>
<button class="btn btn-primary  btn-flat" id="Place_order_btn">Place Order</button>
</form>

function formatRepo (repo) {
  if (repo.loading) {
    return repo.text;
  }

  var $container = $(
    "<div class='select2-result-repository clearfix'>" +
      "<div class='select2-result-repository__meta'>" +
        "<div class='select2-result-repository__title'></div>" +
        "</div>" +
      "</div>" +
    "</div>"
  );

  $container.find(".select2-result-repository__title").text(repo.full_name);
  return $container;
}

function formatRepoSelection (repo) {
  return repo.full_name || repo.text;
}


function attachItems(item_elt){
    
    item_elt = typeof(item_elt) == 'undefined'?'.view_by_item':item_elt;
    $(document).find(item_elt).select2({
        ajax: {
            url: "https://api.github.com/search/repositories",
            dataType: 'json',
            delay: 250,
            data: function (params) {
              return {
                q: params.term, // search term
                page: params.page
              };
            },
            processResults: function (data, params) {
              params.page = params.page || 1;

              return {
                results: data.items,
                pagination: {
                  more: (params.page * 30) < data.total_count
                }
              };
            },
            cache: true
          },
          placeholder: 'Search for a repository',
          minimumInputLength: 3,
          templateResult: formatRepo,
          templateSelection: formatRepoSelection
    });
}
var rowCount = 2;
$(document).on('click', '.plusbutton',function(e){
    e.preventDefault();
    
    rowCount++;
    
    
    var newRow = '<tr>';

    newRow += '<td class="tleft"><select name="view_by_item[]"  data-id="'+rowCount+'"  id="view_by_item'+rowCount+'" class="form-control view_by_item"  style="width: 100%"></select></td>';
    newRow += '<td class="tcenter"><input  type="number" name="qty[]" id="qty'+rowCount+'" class="qty form-control"  style="text-align:right;" /></td>'; 
    newRow += '<td class="tcenter"><input type="text" name="ponum[]" class="ponum form-control"  placeholder="Optional"/></td>';    
   
    $("#myTable tbody").append(newRow);
    attachItems('#view_by_item'+rowCount);
});

attachItems();


$('#CartForm').validate({
    ignore: [],
    rules:{
        '.view_by_item':{required: true},
        '.qty': {required: true}
        },
    submitHandler: function() {
        alert('No errors');
        return false;
        }   
});

JSFiddle链接

jquery-validate jquery-select2
1个回答
0
投票

当使用 jquery 验证动态添加的字段时,请记住它会查找唯一的名称。在您的情况下,使用了 view_by_item[]、qty[]、ponum[],并且每次添加项目时它们都会重复。建议这样做,因为您将数据提交到服务器端并捕获多个字段数据,建议字段名称使用方括号。

为了使 jquery validate 工作,您必须向名称添加索引,例如 view_by_item[0]、view_by_item[1]、view_by_item[2]、... 类似 qty[0]、qty[1]、qty[2] ...等等。这样 jquery 验证器会将其视为唯一字段并应用验证。

您必须添加以下代码才能在单击提交按钮时动态附加验证/规则。

$('#CartForm').on('submit', function(e){
$(document).find('.view_by_item').each(function(){
      $(this).rules("add", {
          required: true,
          messages: {
          required: "Item is required"
        }
      });
});

$(document).find('.qty').each(function(){
      $(this).rules("add", {
        required: true,
        messages: {
        required: "Qty is required"
      }
    });
});

return false;
});

并更改验证方法,如下所示

$('#CartForm').validate({
    ignore: [],
    submitHandler: function() {
        alert('No errors');
        return false;
        }   
});
© www.soinside.com 2019 - 2024. All rights reserved.