jquery serialize collecting multiples form which group values by name

270 views Asked by At

How to collect multiples form input and group the output into string which combines values by name

For example:

<div class="register">
    <input type="text" name="full_name">
    <textarea name="address"></textarea>
    <input type="radio" name="sex" value="male">
    <input type="radio" name="sex" value="female">
    <input type="checkbox" name="hobies" value="foodball">
    <input type="checkbox" name="hobies" value="basketball">
    <input type="button" class="submit" value="Submit">
</div>

how to get the output will be string or something like this

// field_name: [values]

i'm trying like this:

$('.submit').click(function(){
    var InputCollect = $('.register').find(':input');

    $(InputCollect).each(function(){
        names = $(this).attr('name');
        values = $(this).attr('value');
    
        // the output will be string or something like this:
    
        // full_name: jhon doe
        // address: some street
        // gender: male
        // hobies: football, basketball (combine multiple values:not if checked)
    });
});

i don't know how to group multiple values by it's name

what is the best way to make that output.. use jQuery serialize or each function ?? thanks for attention

1

There are 1 answers

4
Hassan On

You can find the checked checkboxes with :checked. You can then put them into a key-value store where the key is the name of the checkbox, and the value is an array of selected checkboxes :

$('.submit').click(function(){
    var InputCollect = $('.register').find(':input');
    let form = {}
    $('input[type=text], textarea, input[type=radio]:checked', '.register').each(function(){
        const name = $(this).attr('name');
        const value = $(this).val();
        if(value.trim() !== '') {
            form[name] = value;
        }
    });
    
    $('input[type=checkbox]:checked', '.register').each(function(){
        const name = $(this).attr('name');
        const value = $(this).val();
        if(form[name] === undefined) {
            form[name] = [value];
        } else {
            form[name].push(value);
        }
    });
    
    console.log(form);
});

Here I had to split the logic into two callbacks because handling textual inputs and radios is different from handling checkboxes, although you can still merge them in a single callback if you want.

JS fiddle link