Reputation: 7
I want to dynamically display the content of a site in relation to choice of visitors when it selects checkbox. No problem for sends information in Ajax and the php side. But I can not create an array like I want in jQuery.
HTML :
<div id="filter">
<div class="sizes">
<input type="checkbox" data-group="size_catalog" data-value="32">
<input type="checkbox" data-group="size_catalog" data-value="36">
<input type="checkbox" data-group="size_catalog" data-value="38">
<input type="checkbox" data-group="size_catalog" data-value="40">
</div>
<div class="colors">
<input type="checkbox" data-group="color_catalog" data-value="red">
<input type="checkbox" data-group="color_catalog" data-value="blue">
<input type="checkbox" data-group="color_catalog" data-value="black">
</div>
</div>
The object with multiple array I would like to have (it is necessary to group the same data-group) :
var myArray = {size_catalog : ["32", "36", "38"], color_catalog: [red, blue]};
My current code (found on the internet and adapted) that create a simple array:
function getChecked(){
var opts= [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.value);
}
});
return opts;
}
function updateSearch(opts){
$.ajax({
type: "POST",
url: "class.search.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
...
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getChecked();
updateSearch(opts);
});
updateSearch();
Thank you for your help!
Upvotes: 0
Views: 888
Reputation: 318182
You do that by iterating and creating an object with the size-catalog
as keys, and an array you push to as a value.
var $checkboxes = $("input:checkbox");
$checkboxes.on('change', function() {
var obj = {};
$checkboxes.filter(':checked').each(function() {
var n = $(this).data('group'),
v = $(this).data('value');
n in obj ? obj[n].push( v ) : obj[n] = [v];
});
$.post('class.search.php', {filterOpts: obj}, 'json').done(function(records) {
});
});
Upvotes: 2
Reputation: 48415
Thats not a multidimentional array, thats an object containing 2 different arrays. If you want that, then something like this is what you want:
function getChecked() {
var sizeArray = [];
var colorArray = [];
$checkboxes.each(function() {
if ($(this).is(':checked')) {
if ($(this).data('group') == 'size_catalog')
sizeArray.push($(this).data('value'));
else if ($(this).data('group') == 'color_catalog')
colorArray.push($(this).data('value'));
}
});
return {
size_catalog: sizeArray,
color_catalog: colorArray
};
}
Upvotes: 0