I currently have a json file that contains the inventory of vehicles. I have a search page that allows the users to filter the inventory using checkboxes, such as make, model, color, etc..
Thanks to my previous question: PHP filter JSON array with $_POST array, I can filter the results, and what seemed like a simple change on the javascript side has been a challenge.
I need to pass the checkbox values as an array. For example, if I select Mustang and Camaro checkboxes, it would need to be 'Model' => ['Mustang', 'Camaro'].
I tried to create 2 arrays. One for the keys, (Make, Model, Color), etc... and another for each of the values, (Mustang and Camaro). Some values may have one item, some may have several. For example, if we wanted all red Mustang's and Camaro's, the array should look like:
$filters = ['Model' => ['Mustang', 'Camaro'],Color' => ['Red']];
Or, just red Mustangs:
$filters = ['Model' => ['Mustang'],Color' => ['Red']];
I can loop each of the checkboxes, and I attempted to put all the checkbox names (data.id) as a key, and a second array (data.value) as the values. If the key exists, then add each of the values that have the same key.
$("[name='checkBoxItem']").each(function (index, data) {
if (data.checked) {
var kv=[]; // Keys
var vv=[]; // Array of the values for each key.
// data.id is the key of selection, ie, Model, Color, etc...
// data.value is the value for each checkbox selection, ie, Mustang, Camaro
console.log(data.id + data.value);
// This returns:
// Model Mustang
// Model Camaro
// Color Red
// Needs to be:
// $filters = [
// 'Model' => ['Mustang', 'Camaro'],
// 'Color' => ['Red']
// ];
if(!(data.id in kv)){ // Is always called.
alert("Does't exist, adding : " + data.value);
kv.push(data.id);
vv.push(data.value);
} else {
vv.push(data.value);
}
checked.push({[kv]: vv});
}
});
My code returns:
Array ( [selected_values] => Array([0] => Array ([Make] => Array([0] => Mustang))))
Which is close, but if(!(data.id in kv)) is always being called, preventing me from adding multiple selections.
I am sorry if I am having coders block on something that I should have been able to do.
Aucun commentaire:
Enregistrer un commentaire