I have a div filled with buttons. The value of these buttons represent widht and height of a product. I'm trying to split up the buttons, sorting them by their width, which is the first value in the html.
So this:
<div id="flagSize">
<button id="0">100x200cm</button>
<button id="1">100x250cm</button>
<button id="2">100x300cm</button>
<button id="3">100x350cm</button>
<button id="4">100x400cm</button>
<button id="5">110x300cm</button>
<button id="6">120x300cm</button>
<button id="7">120x350cm</button>
<button id="8">120x400cm</button>
<button id="9">140x400cm</button>
<button id="10">150x400cm</button>
</div>
Has to become this:
<div id="flagSize">
<div class="buttonGroup">
<button id="0">100x200cm</button>
<button id="1">100x250cm</button>
<button id="2">100x300cm</button>
<button id="3">100x350cm</button>
<button id="4">100x400cm</button>
</div>
<div class="buttonGroup">
<button id="5">110x300cm</button>
</div>
<div class="buttonGroup">
<button id="6">120x300cm</button>
<button id="7">120x350cm</button>
<button id="8">120x400cm</button>
</div>
<div class="buttonGroup">
<button id="9">140x400cm</button>
</div>
<div class="buttonGroup">
<button id="10">150x400cm</button>
</div>
</div>
To do this I figured I first have to get the content of the button, splitting it at the X. I then put this value in to an array combined with the ID of the element.
var orderSizes = [];
$('#flagSize button').each(function(){
var widthValue = $(this).html();
widthValue = widthValue.split('x');
var orderItem = [widthValue[0],$(this).attr('id')]
orderSizes.push(orderItem);
});
console.log(orderSizes);
I now have to check the values of this array and if they are the same as other items in the array, put them together in a div with the class buttonGroup. This is the part where I'm stuck.
Any help with this, or a different, better aproach would be greatly appreciated.
Try something like
//a cache holder to hold the wrappers to that it can be reused
var wrappers = {};
$('#flagSize button').each(function () {
var widthValue = $.trim($(this).html());
widthValue = widthValue.split('x')[0];
var wrapper = wrappers[widthValue];
//if the wrapper does not exists create one and add it after the current element
if (!wrapper) {
wrappers[widthValue] = wrapper = $('<div class="buttonGroup"></div>').insertAfter(this);
}
//move the element to the respective wrapper
wrapper.append(this)
});
Demo: Fiddle
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments