JS 获取Form表单信息序列化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../select2/css/select2.min.css" rel="stylesheet">



    <script src="../js/jquery-1.11.1.min.js"></script>
    <script src="../bootstrap/js/bootstrap.min.js"></script>
    <script src="../select2/js/select2.min.js"></script>

</head>
<body>
<form id="f1">
<div class="row">
    <div class="col-lg-3">
        <select class="form-control" name="d1" data-tags="true" data-placeholder="Select an option" data-allow-clear="true" id="d1"></select>
    </div>
    <div class="col-lg-3">
        <select class="form-control" name="d2" data-tags="true" data-placeholder="Select an option" data-allow-clear="true" id="d2"></select>
    </div>
    <div class="col-lg-3">
        <select class="form-control" name="d3" data-tags="true" data-placeholder="Select an option" data-allow-clear="true" id="d3"></select>
    </div>
    <input name="d4" id="d4">
<button id="but"  class="btn-danger">btn</button>
</div>
</form>
<script>
    $(function () {
        var data = [{ id: 0, text: '0',code:[{id:'00',text:'00'},{id:'01',text:'01'}] }, { id: 1, text: '1' }, { id: 2, text: '2' }];
        $('#d1').select2({
            data:data
        });
        $('#d2').select2({
            data:data
        });
        $('#d3').select2({
            data:data
        });
        $('#but').click(function(){
            alert(JSON.stringify(getFormJson("#f1")));
        })


        $.fn.serializeObject = function()
        {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };
    })
    function getFormJson(frm) {
        var o = {};
        var a = $(frm).serializeArray();

        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }


        });
        return o;
    }
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/SunmmerSoftware/article/details/51854946