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