javascript如何使用键和复选框值创建多维数组

时间:2018-01-24 13:18:09

标签: javascript jquery html arrays ajax

我需要帮助来创建通过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>

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

4 个答案:

答案 0 :(得分:1)

您可以使用数组,而不是使用对象保存值,例如示例...

&#13;
&#13;
$(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');
    }
});


}

}
&#13;
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以为多维数组创建列,然后将其字符串化为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));
});

答案 2 :(得分: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的来电者将被告知结果。

答案 3 :(得分:0)

如果您仍需要对象,可以尝试this

&#13;
&#13;
$(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();
  })
});
&#13;
.optschecks {
  display: inline-block;
  margin: 3px 0;
  text-align: left;
  width: 100%;
}

.opts_qty {
  width: 50px;
}

.showerror,
.opts_qty {
  display: none;
}
&#13;
    <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>
&#13;
&#13;
&#13;