js获取form表单数据和form表单赋值

$.fn.extend({
// 调用方式:$("xxxxx").getform();

     getform: function () {                   
        var obj = {};
        var array = $(this).serializeArray();
        $.each(array, function () {
            obj[this.name] = this.value;
        });
        return obj;
    },              
            // 调用方式: $("xxx").setform(json);

            setform: function (jsonValue) {
        var obj = this;
        $.each(jsonValue, function (name, ival) {
            var $input = obj.find("input:[name=" + name + "]");
            if ($input.attr("type") == "radio" || $input.attr("type") == "checkbox") {
                $input.each(function () {
                    if (Object.prototype.toString.apply(ival) == '[object Array]') { // 是复选框,并且是数组  
                        for (var i = 0; i < ival.length; i++) {
                            if ($(this).val() == ival[i])
                                $(this).attr("checked", "checked");
                        }
                    } else {
                        if ($(this).val() == ival)
                            $(this).attr("checked", "checked");
                    }
                });
            } else if ($input.attr("type") == "textarea") { // 多行文本框  
                obj.find("[name=" + name + "]").html(ival);
            } else {
                obj.find("[name=" + name + "]").val(ival);
            }
        });
    }

});

猜你喜欢

转载自blog.51cto.com/8201468/2132158