使用字段总和进行表单验证

时间:2015-09-29 11:10:09

标签: javascript jquery html validation

我正在尝试使用此验证码。我只希望用户能够在字段总和等于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');
          }
      }
    });
 }
 );

1 个答案:

答案 0 :(得分:2)

以下是两种方法:

(未添加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!
    }
});

JSFIDDLE EXAMPLE

示例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();
    }

});

UPDATED JSFIDDLE

更新(在评论部分谈论):

JSFIDDLE EXAMPLE