开发者

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

开发者 https://www.devze.com 2023-04-07 18:43 出处:网络
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.

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?


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(',');
});


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;

}
0

精彩评论

暂无评论...
验证码 换一张
取 消