JQ获取checkbox 转换数组格式


JQ 自动获取checkbox 获得的数组是这样的 (多组)
0: Object { name: "name1", value: "value3" }
1: Object { name: "name1", value: "value4" }
2: Object { name: "name2", value: "value1" }
length: 3
 
而我目标数组是  name[value1,value2]这样
name1: Array [ "value3", "value4" ]
name2: Array [ "value1" ]
 
 
源码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
</head>
<body>
    <form action="" method="post" id="form">
        <input type="checkbox" name="name1" value="value1" onclick="c()"/>11
        <input type="checkbox" name="name1" value="value2" onclick="c()"/>11
        <input type="checkbox" name="name1" value="value3" onclick="c()"/>11
        <input type="checkbox" name="name1" value="value4" onclick="c()"/>11
        <input type="checkbox" name="name2" value="value1" onclick="c()"/>11
        <input type="checkbox" name="name2" value="value2" onclick="c()"/>11
        
    </form>
    <script src="jquery.min.js"></script>
    <script type="text/javascript">
        function c(){
            var arr = $('#form').serializeArray();
            console.log(arr)
            var obj = {};
            for (var i =0 ; i<arr.length;i++) {
                obj[arr[i]['name']] =[];
                //根据name 自动生成数组
            }
            for (var index in obj){
                //便利数组赋值
                for (var i =0 ; i<arr.length;i++) {
                    if(arr[i]['name']==index){
                        obj[index].push(arr[i]['value'])
                    }
                }
            }
            console.log(obj)
        }
        

    </script>
</body>
</html>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM