There is such a html

<label for="val-1" class="mr-sm"> <input type="checkbox" name="attributes" value="1" data-attribute-name="size" id="val-1" class="js-product-attributes" >10 </label> <label for="val-2" class="mr-sm"> <input type="checkbox" name="attributes" value="2" data-attribute-name="color" id="val-2" class="js-product-attributes" >Red </label> 

There are n checkboxes

and here is the js code

  var $combination = {}; $('.js-product-attributes:checked').each(function (i, el) { $combination[$(el).data('attribute-name')] = {}; }); console.log($combination); 

As a result, I get

 Object {Size: Object, Color: Object} Color: Object Size:Object __proto__: Object 

The question itself is how to add elements of this object to an array of selected checkboxes whose data-attribute-name corresponds to the name of the element in the object. Object.color to Object.color add all selected checkboxes with data-attribute-name="color" . Thank!

  • Object.color is an array? - Horchynskyi

1 answer 1

So?

 var $combination = {}; $('.js-product-attributes').each(function (i, el) { $combination[$(el).data('attribute-name')] = {}; }); function PuchCheck(){ let color = $('.js-product-attributes[data-attribute-name = color]:checked'), size = $('.js-product-attributes[data-attribute-name = size]:checked'); $combination.color = color; $combination.size = size; console.log($combination.color.length+' '+$combination.size.length); $($combination.color).parent().css({'color':'red'}); $($combination.size).parent().css({'color':'blue'}); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="val-1" class="mr-sm"> <input type="checkbox" name="attributes" value="1" data-attribute-name="size" id="val-1" class="js-product-attributes" >10 </label> <label for="val-2" class="mr-sm"> <input type="checkbox" name="attributes" value="2" data-attribute-name="color" id="val-2" class="js-product-attributes" >Red </label> <label for="val-3" class="mr-sm"> <input type="checkbox" name="attributes" value="2" data-attribute-name="color" id="val-3" class="js-product-attributes" >Grey </label> <label for="val-4" class="mr-sm"> <input type="checkbox" name="attributes" value="2" data-attribute-name="color" id="val-4" class="js-product-attributes" >Green </label> <button onclick="PuchCheck()">Push</button>