'Is it possible to have a form submit a comma separated list via GET?

Let's say I have a form that contains a whole bunch of check boxes with the same name, c. Each checkbox has an integer value assigned to it.

When the form is submitted, via GET, I'd like the url to look like www.url.com/?c=1,2,3,4,5

and not

www.url.com/?c=1&c=2&c=3&c=4&c=5

Possible? or will I have to capture the form submit via jQuery, loop through each checked box, and tack on my own url var?



Solution 1:[1]

You'll have to resort to Javascript to accomplish this.

In jQuery, this is how you might go about it:

$('form').submit(function()
{
    var values = [];

    $(this).find('input[type="checkbox"][name="c"]:checked').each(function()
    {
        values.push(this.value);
    });

    window.location = 'www.url.com/?c=' + values.join(',');
});

Solution 2:[2]

function form_to_submit() {

        var form_to_submit = $('#form');

        var queryArray = form_to_submit.serializeArray();

        const queryArrayReduced = queryArray.reduce((acc, {name, value}) => 
        {

            if(name in acc) {
            acc[name] = acc[name].concat(','+value);
            } else {
            acc[name] ??= value;
            }

            return acc;
        }, {});

        var queryString = decodeURIComponent($.param(queryArrayReduced));

        window.location.href = '?' + queryString;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Vikrant Shitole