[英]javascript How to create multidimensional array with key and checkboxes values
I need help to create array which to be passed via ajax to php page. 我需要帮助来创建要通过ajax传递到php页面的数组。
here is my html 这是我的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>
If you run the snippet you will see its working but out of the loop the array consist only ID + 1 selected option. 如果运行该代码段,您将看到它的正常运行,但循环之外,该阵列仅包含ID + 1个所选选项。 If the customer selects more than 1 option it is not saved.
如果客户选择了多个选项,则不会保存该选项。 How to add all selected options?
如何添加所有选择的选项? AND something else I can not manage - how to add the quantity for each product option which is selected to the array?
还有其他我无法管理的事情-如何为阵列中选择的每个产品选项添加数量? Thank you for your help and time !
谢谢您的帮助和时间!
Instead of using an object to save your values you could use an array, like the example... 除了使用对象来保存值外,还可以使用数组,例如示例...
$(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>
You can create columns for multidimensional array then stringify it as JSON 您可以为多维数组创建列,然后将其字符串化为JSON
$(".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));
});
You can avoid a lot of messing about by better exploiting jQuery collections and their methods. 通过更好地利用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
}
}
By returning a promise, addtocart's caller is kept informed of the outcome. 通过返回承诺,addtocart的呼叫者可以随时了解结果。
If you still need an object you can try 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.