简体   繁体   English

jquery序列化收集倍数形式,按名称对值进行分组

[英]jquery serialize collecting multiples form which group values by name

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 ??制作该输出的最佳方法是什么.. 使用 jQuery 序列化或每个函数? thanks for attention谢谢关注

You can find the checked checkboxes with :checked .您可以使用: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 JS小提琴链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM