function HTMLFormElement(){
this.init();
return this.json;
}
HTMLFormElement.prototype.init = function(){
this.json = {};
this.inputs = document.querySelectorAll("input");
this.texts = document.querySelectorAll("textarea");
this.sels = document.querySelectorAll("select");
this.types = ['checkbox', 'color', 'date', 'datetime', 'datetime-local', 'month', 'week', 'time', 'email', 'file', 'hidden', 'number', 'password', 'radio', 'range', 'search', 'tel', 'text', 'url'];
this.SerializedJson();
};
HTMLFormElement.prototype.SerializedJson = function() {
if (this.inputs.length > 0 || this.texts.length > 0) {
this.getInputsValue();
this.getTextValue();
this.getSelsValue();
}
};
HTMLFormElement.prototype.getInputsValue = function(){
var input;
for (var i = 0; i < this.inputs.length; i++) {
input = this.inputs[i];
var name = input.getAttribute("name");
var type = input.getAttribute("type");
if (type && name && this.types.indexOf(type.toLowerCase()) > -1) {
if (type != 'checkbox' && type != 'radio') {
this.json[name] = input.value;
} else if (type == 'radio') {
if (!this.json[name]) {
this.json[name] = '';
}
if (input.checked) {
this.json[name] = input.value;
}
} else if (type == 'checkbox') {
if (!this.json[name]) {
this.json[name] = '';
}
if (input.checked) {
if (this.json[name]) {
this.json[name] += "," + input.value
} else {
this.json[name] = input.value;
}
}
}
}
}
}
HTMLFormElement.prototype.getTextValue = function(){
for (var i = 0; i < this.texts.length; i++) {
input = this.texts[i];
var name = input.getAttribute("name");
if (name) {
this.json[name] = input.value;
}
};
};
HTMLFormElement.prototype.getSelsValue = function(){
for (var i = 0; i < this.sels.length; i++) {
input = this.sels[i];
var name = input.getAttribute("name");
if (name) {
this.json[name] = input.value;
}
}
return this.json;
}
使用方法:
new HTMLFormElement());