HTMLFormElement获取表单里面所有的值然后以json形式返回

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());

 

转载于:https://www.cnblogs.com/rainheader/p/4670193.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值