简体   繁体   中英

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.

here is my 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. 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

Working 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));
});

You can avoid a lot of messing about by better exploiting jQuery collections and their methods.

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.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM