I want to change a query string from
?firstArray[]=0001&firstArray[]=0002&secondArray[]=0003&secondArray[]=0004 to ?firstArray=0001,0002&secondArray=0003,0004
I think I'm almost there, but the problem I have is that the array values are the same for both arrays after my javascript is done processing the form. Here's the form:
<form method="get" action="" class="productFilter">
<input type="checkbox" name="firstArray[]" id="" value="0001">0001
<input type="checkbox" name="firstArray[]" id="" value="0002">0002
<input type="checkbox" name="secondArray[]" id="" value="0003">0003
<input type="checkbox" name="secondArray[]" id="" value="0004">0004
<input type="submit" name="submit" value="test">
</form>
And here's the javacript/jquery:
$('.productFilter').on('submit', function() {
var newVal = [];
var seen = {};
// Gather values into array.
$('input[name$="[]"]:checked').each(function() {
newVal.push($(this).val());
});
// Make comma-separated list of values.
var commaSeparated = newVal.join(',');
console.log(commaSeparated);
// Remove duplicates so an 'array' is only listed once in the query string.
$('input[name$="[]"]:checked').each(function() {
var name = $(this).attr('name');
if (seen[name]) {
$(this).remove();
}
else {
seen[name] = true;
}
$(this).attr('name', name.slice(0, -2)).val(commaSeparated);
});
});
I understand why my 'commaSeparated' var contains the values of both the firstArray and secondArray inputs, so when I check all the boxes, the resulting query string is:
?firstArray=0001,0002,0003,0004&secondArray=0001,0002,0003,0004 when I want it to be ?firstArray=0001,0002&secondArray=0003,0004
I'm not sure how to fix it though. I would need to store the values of the form arrays in separate variables, right? It should be noted that I don't know how many form elements there will be and what they will be called in my production code.