zoukankan      html  css  js  c++  java
  • 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());

  • 相关阅读:
    Rust 总章
    GO 总章
    vue引入d3
    echarts地图修改高亮颜色及区域界线颜色
    vue+element 树形穿梭框组件
    element表格上下固定,内容高度自适应
    echarts在dialog弹框中不显示的解决方案
    echarts 饼图给外层加边框
    selenium等待元素出现
    Pycharm永久激活
  • 原文地址:https://www.cnblogs.com/rainheader/p/4670193.html
Copyright © 2011-2022 走看看