I'm strugling with this for over a day now and can't get it working. I want to create a multidimensional javascript array that hold filter variables that must be pharsed to php for AJAX calls. The goal is to make a product filter and filter out products that don't apply to the filter variables.
The last part is php and I know how to solve that. But I'm struggling with creating a javascript array that holds all the selected filter variables.
I have a filter_ID and a filter_value_ID. Withing a filter, for example size, there can be different values like S, M, L, XL etc.
So I want a array like this:
filterArr = array(
[4] => array(10,20,30)
[8] => array(4)
[20] => array(2,3, 7)
)
The array must be filled when a user check a checkbox. I managed it almost, but the problem is that I'm getting null items in the array, because I cant get the filterID in the array.
My code is on JSFiddle: http://jsfiddle.net/VCfjp/
The part where it is going wrong is on line 10, 11, 12:
if (!(filterID in filter)) {
filter[filterID] = [];
}
I'm running stuck at the moment. I would know how to do it in PHP, but can't get it working in javascript. Some help is appreciated! Offcourse I've been looking at other threads on the forum, but can't find anything matching.
1 Answer 1
Hash arrays in JS are defined as object, so use it like this:
var object = {
4: [10,20,30],
8: [4],
20: [2,3,7]
};
Just observe what PHP would ouput when issuing:
echo json_encode(array(
[4] => array(10,20,30)
[8] => array(4)
[20] => array(2,3, 7)
));
The code you requested:
jQuery(document).ready(function($) {
var hashArray = {};
$('.myCheckbox').on('change', function() {
var self = $(this),
checkboxId = parseInt(self.attr('data-id')), // since you used it as a number above
checkboxValue = parseInt(self.val()); // since you also used it as a number above
if (self.is(':checked')) {
// add to array
if (!hashArray.hasOwnProperty(checkboxId)) hashArray[checkboxId] = [];
hashArray[checkboxId].push(checkboxValue);
}
else {
if (hashArray.hasOwnProperty(checkboxId)) {
// remove from array if it exists
hashArray[checkboxId].splice(hashArray[checkboxId].indexOf(checkboxValue), 1);
}
}
});
});
5 Comments
Explore related questions
See similar questions with these tags.
var items = [[1,2],[3,4],[5,6]];