带有字段和的表单验证



我试图让这个验证代码工作。我只希望用户能够添加到购物车时,字段的总和等于7,如果它不等于7,那么一个错误应该显示。

任何帮助将是伟大的,因为我不知道我需要改变它。

JSFiddle

$('#button-cart').on('click', function() {
          var $fieldsSet = $('div.validateFields');
          var MaxSelectionNum = "7"
          var sum = 0;
          // Loop through all inputs with names that start
          // with "option-quantity" and sum their values
          $fieldsSet.find('input[name^="option-quantity"]').each(function() {
              sum += parseInt($(this).val()) || 0;
          });
          // Set the sum
          $fieldsSet.find('.sum').val(sum);
          var allSumEqualCustomDesc = true;
          if (allSumEqualCustomDesc) {
              $("div.errorQuantity").html("Please select 7 meals").show();
          } else {
              $("div.errorQuantity").hide();
          };
  $.ajax({
      url: 'index.php?route=checkout/cart/add',
      type: 'post',
      data: $('#product input[type='text'], #product input[type='number'], #product input[type='hidden'], #product input[type='radio']:checked, #product input[type='checkbox']:checked, #product select, #product textarea'),
      dataType: 'json',
      beforeSend: function() {
          $('#button-cart').button('loading');
      },
      complete: function() {
          $('#button-cart').button('reset');
      },
      success: function(json) {
          $('.alert, .text-danger').remove();
          $('.form-group').removeClass('has-error');
          if (json['error']) {
              if (json['error']['option']) {
                  for (i in json['error']['option']) {
                      var element = $('#input-option' + i.replace('_', '-'));
                      if (element.parent().hasClass('input-group')) {
                          element.parent().after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                      } else {
                          element.after('<div class="text-danger">' + json['error']['option'][i] + '</div>');
                      }
                  }
              }
              if (json['error']['recurring']) {
                  $('select[name='recurring_id']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
              }
              // Highlight any found errors
              $('.text-danger').parent().addClass('has-error');
          }
          if (json['success']) {
              $('.breadcrumb').after('<div class="alert alert-success">' + json['success'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');
              $('#cart > button').html('<i class="fa fa-shopping-cart"></i> ' + json['total']);
              $('html, body').animate({
                  scrollTop: 0
              }, 'slow');
              $('#cart > ul').load('index.php?route=common/cart/info ul li');
          }
      }
    });
 }
 );

有两种方法:

(没有添加AJAX代码,但我已经评论了它应该去的地方)

示例1:

$('#button-cart').on('click', function()
{
    var MaxSelectionNum = "7";
    var sum = 0;
    // Loop through all inputs with names that start
    // with "option-quantity" and sum their values
    $('input[name^="option-quantity"]').each(function()
    {
        console.log(parseInt($(this).val()));
        sum += parseInt($(this).val()) || 0;
    });
    if (sum < MaxSelectionNum)
    {
        $(".errorQuantity").html("Please select 7 meals").show();
    }
    else
    {
        $(".errorQuantity").hide();
        // AJAX SHOULD GO HERE!
    }
});
<<p> JSFIDDLE例子/strong>

示例2:(更接近你的原始代码)

$('#button-cart').on('click', function()
{
    var MaxSelectionNum = "7";
    // Set the sum
    var sum = 0;
    // Loop through all inputs with names that start
    // with "option-quantity" and sum their values
    $('input[name^="option-quantity"]').each(function()
    {
        console.log(parseInt($(this).val()));
        sum += parseInt($(this).val()) || 0;
    });
    $(".sum").html(sum);  
    if ($(document).find('.sum').val(sum) > MaxSelectionNum)
    {
        $(".errorQuantity").hide();
        // AJAX SHOULD GO HERE!
    }
    else
    {
        $(".errorQuantity").html("Please select 7 meals").show();
    }
});

更新JSFIDDLE

已更新(在评论部分讨论):

<<p> JSFIDDLE例子/strong>

最新更新