【问题标题】:javascript How to create multidimensional array with key and checkboxes valuesjavascript 如何使用键和复选框值创建多维数组
【发布时间】:2018-07-03 13:21:24
【问题描述】:

我需要帮助来创建要通过 ajax 传递到 php 页面的数组。

这是我的html

$(document).ready(function() {
  $('.p_options').change(function() {
    if ($(this).is(":checked")) {
      $(this).next(".opts_qty").val(1).show();
    } else $(this).next(".opts_qty").val(0).hide();
  })
});
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function addtocart(id){
 arr = {};
 var error = 0;
 var checked = 0;
if ($('.p_options').length) {

  $('.p_options').each(function() {
    if ($(this).is(":checked")) {
      var num = $(this).next(".opts_qty").val();
      if (num !== '' && num > 0) {
        //info[id].push($(this).val());
        arr[id] = $(this).val();
        checked++;
        $(this).next(".opts_qty").css('background', '#fff');
      } else {
        $(this).next(".opts_qty").css('background', 'red');
        error++;
      }
      
    }
  });
  alert(JSON.stringify(arr));

}
if(error < 1){
$.ajax({
    type: "post",
    url: "./shop/basket.php",
	data: { "product": id ,  'product_options':arr},
    dataType: 'json',
    cache: false,
    success: function(data){
	alert('success');
    }
});


}

}
</script>
<div class="inprd">Please select from options for Size
  <label class="optschecks">
    <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">    
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
  <label class="optschecks">
    <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
    <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
  </label>
</div>
<span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

如果您运行 sn-p,您将看到它正在工作,但在循环之外,该数组仅包含 ID + 1 个选定选项。如果客户选择超过 1 个选项,则不会保存。如何添加所有选定的选项?还有其他一些我无法管理的东西 - 如何将每个产品选项的数量添加到数组中? 感谢您的帮助和时间!

【问题讨论】:

    标签: javascript jquery html arrays ajax


    【解决方案1】:

    您可以通过更好地利用 jQuery 集合及其方法来避免很多麻烦。

    function addtocart(id) {
        var $checked = $('.p_options').filter(':checked');
        $checked.next(".opts_qty").css('background', '#fff'));
        var $badns = $checked.filter(function() {
            return !(+$(this).next(".opts_qty").val()); // anything falsy is bad
        }).next(".opts_qty").css('background', 'red');
        if($badns.length === 0) {
            var product_options = $checked.get().map(function(opt) {
                var object = {};
                object[opt.value] = $(opt).next(".opts_qty").val(); // from RenzoCC's answer
                return object;
            });
            return $.ajax({ // don't forget to return the jqXHR (promise)
                type: 'post',
                url: './shop/basket.php',
                data: { 'product':id, 'product_options':product_options},
                dataType: 'json',
                cache: false
            });
        } else {
            return $.Deferred().reject(new Error('no options selected')).promise(); // and return a rejected promise if validation fails
        }
    }
    

    通过返回一个承诺,addtocart 的调用者会被告知结果。

    【讨论】:

      【解决方案2】:

      如果你还需要一个对象,你可以试试this

      $(document).ready(function() {
        $('.p_options').change(function() {
          if ($(this).is(":checked")) {
            $(this).next(".opts_qty").val(1).show();
          } else $(this).next(".opts_qty").val(0).hide();
        })
      });
      .optschecks {
        display: inline-block;
        margin: 3px 0;
        text-align: left;
        width: 100%;
      }
      
      .opts_qty {
        width: 50px;
      }
      
      .showerror,
      .opts_qty {
        display: none;
      }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
      </script>
      <script>
        function addtocart(id) {
          arr = {};
          var error = 0;
          var checked = 0;
          if ($('.p_options').length) {
            $('.p_options').each(function() {
              if ($(this).is(":checked")) {
                var num = $(this).next(".opts_qty").val();
                if (num !== '' && num > 0) {
                  if (!arr[id])
                    arr[id] = []
                  arr[id].push({
                    item: $(this).val(),
                    qty: num
                  });
                  checked++;
                  $(this).next(".opts_qty").css('background', '#fff');
                } else {
                  $(this).next(".opts_qty").css('background', 'red');
                  error++;
                }
              }
            });
            alert(JSON.stringify(arr));
          }
          if (error < 1) {
            $.ajax({
              type: "post",
              url: "./shop/basket.php",
              data: {
                "product": id,
                'product_options': arr
              },
              dataType: 'json',
              cache: false,
              success: function(data) {
                alert('success');
              }
            });
          }
        }
      </script>
      <div class="inprd">Please select from options for Size
        <label class="optschecks">
          <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
          <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
        </label>
        <label class="optschecks">
          <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
          <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
        </label>
        <label class="optschecks">
          <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
          <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
        </label>
      </div>
      <span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

      【讨论】:

        【解决方案3】:

        您可以为多维数组创建列,然后将其字符串化为 JSON

        工作jsfiddle

        $(".add_to_cart").click(function(){
            arr = [];
            var error = 0;
            var checked = 0;
            $('.p_options').each(function() {
                 if ($(this).is(":checked")) {
                 var num = $(this).next(".opts_qty").val();
                    if (num !== '' && num > 0) {
                      arr.push({
                        Item : $(this).val(), 
                        Quantity : num
                      });
                    }
                 }
            });
            alert(JSON.stringify(arr));
        });
        

        【讨论】:

          【解决方案4】:

          您可以使用数组来代替使用对象来保存值,例如示例...

          $(document).ready(function() {
            $('.p_options').change(function() {
              if ($(this).is(":checked")) {
                $(this).next(".opts_qty").val(1).show();
              } else $(this).next(".opts_qty").val(0).hide();
            })
          });
          
          
          function addtocart(id){
           arr = [];
           var error = 0;
           var checked = 0;
          if ($('.p_options').length) {
          
            $('.p_options').each(function() {
              if ($(this).is(":checked")) {
                var num = $(this).next(".opts_qty").val();
                if (num !== '' && num > 0) {
                  //info[id].push($(this).val());
                  var object = {};
                  object[''+$(this).val()] = num;
                  arr.push(object);
                  checked++;
                  $(this).next(".opts_qty").css('background', '#fff');
                } else {
                  $(this).next(".opts_qty").css('background', 'red');
                  error++;
                }
                
              }
            });
            alert(JSON.stringify(arr));
          
          }
          if(error < 1){
          $.ajax({
              type: "post",
              url: "./shop/basket.php",
          	data: { "product": id ,  'product_options':arr},
              dataType: 'json',
              cache: false,
              success: function(data){
          	alert('success');
              }
          });
          
          
          }
          
          }
          .optschecks {
            display: inline-block;
            margin: 3px 0;
            text-align: left;
            width: 100%;
          }
          
          .opts_qty {
            width: 50px;
          }
          
          .showerror,
          .opts_qty {
            display: none;
          }
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
          <script>
          
          </script>
          <div class="inprd">Please select from options for Size
            <label class="optschecks">
              <input type="checkbox" value="S - 16 mm" name="options[]" class="p_options" data="2617"> S - 16 mm
              <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">    
            </label>
            <label class="optschecks">
              <input type="checkbox" value=" M - 17mm" name="options[]" class="p_options" data="2617"> M - 17mm
              <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
            </label>
            <label class="optschecks">
              <input type="checkbox" value=" L- 18 mm" name="options[]" class="p_options" data="2617"> L- 18 mm
              <input type="number" min="0" class="opts_qty" value="" name="opts_qty[]">
            </label>
          </div>
          <span class="add_to_cart_container ib"><button onclick="addtocart(this.id);" name="ring" id="2617" class="add_to_cart" price="52.00" type="button">Add to basket</button></span>

          【讨论】:

          • 谢谢 RenzoCC,它的工作方式是这样的,但是我怎样才能向这个数组添加数量,所以最后有例如 ["S - 16 mm":"1"," M - 17mm": 2] ?
          • 我已经更正了脚本,您可以将对象推送到数组中以达到该结果..如果对您有帮助,请点赞..
          • 非常感谢 RenzoCC!
          猜你喜欢
          • 1970-01-01
          • 2011-08-08
          • 2016-08-29
          • 2013-04-29
          • 1970-01-01
          • 1970-01-01
          • 2012-01-15
          • 2017-06-01
          • 2014-05-20
          相关资源
          最近更新 更多