javascript 提取表单元素生成用于提交的对象(序列化 html 表单)

function serialize(f) {
    var o = {};
    var s = f.getElementsByTagName("select");
    for (var i = 0; i < s.length; i++) {
        var si = s[i];
        var n = si.name;
        if (!si.multiple) {
            o[n] = si.value;
            continue;
        }
        o[n] = [];
        var ops = si.options;
        for (var j = 0; j < ops.length; j++) {
            var oj = ops[j];
            if (oj.selected) {
                o[n].push(oj.value || oj.text);
            }
        }
    }
    var r = f.querySelectorAll("input");
    for (var i = 0; i < r.length; i++) {
        var ri = r[i];
        var n = ri.name;
        if (!(n in o)) {
            if (ri.type === "checkbox") {
                o[n] = [];
            } else {
                o[n] = "";
            }
        }
        switch (ri.type) {
            case "radio":
                if (o[n]) {
                    continue;
                }
                if (ri.checked) {
                    o[n] = ri.value || "on";
                }
                break;
            case "checkbox":
                if (ri.checked) {
                    o[n].push(ri.value || "on");
                }
                break;
            default:
                o[n] = ri.value;
                break;
        }
    }
    return o;
}

 

  

posted @ 2016-11-24 19:24  大胡子毛绒老头  阅读(402)  评论(0编辑  收藏  举报