• Como Crear Un Form Dinamico En Javascript

    Hoy voy a ser bueno y voy a entregar un poco de source code de mi framework. Vamos a ver como hacer un form dinamico en javascript estilo Ext JS usando un poco de DOM y otro de JSON.

    Vamos directamente al codigo, primero el source code de un par de metodos utiles.

    // utils
    function tag(tagName) {
     return document.createElement(tagName);
    } 
    
    function div(id) {
     var dom = tag(tagName);
     dom.id = id;
     return dom;
    }
    
    function get(id) {
     return document.getElementById(id);
    }
    

    Ahora css base para el form.

    .form-container {
    	border: 1px solid #ccc;
    	border-top: none;
    }
    
    .form-title {
    	background: #ccc;
    	height: 22px;
    	line-height: 22px;
    	font-weight: bold;
    	padding-left: 10px;
    }
    
    .form-body {
    	background: #fff;
    }
    
    .form-body-label {
    	text-align: left;
    	clear: left;
    	float :left;
    }
    
    .form-body-field-container {
    	padding-left: 80px;
    	margin-bottom: 4px;
    }
    
    .form-body-buttons {
    	margin-top: 7px;
    	text-align: center;
    }
    

    Ahora el codigo del widget usando las utilidades. La idea de este widget es que pueda crearse una seccion dentro de un DIV donde podamos dibujar un formulario con titulo y una serie de campos verticales tipo text, combo o checkbox. Obviamente agreguen otros componentes si los necesitan.

    /** constructor, canvas es el ID
    Form = function(canvas, options) {
    	this.canvas = get(canvas);
    	this.options = options;
    	this.init();
    }
    
    Form.prototype.init = function() {
    	this.drawContainer();
    	this.drawTitleBar();
    	this.drawBody();
    }
    
    Form.prototype.drawContainer = function() {
    	this.canvas.style.width = this.options.width;
    	this.canvas.className = "form-container";
    }
    
    Form.prototype.drawTitleBar = function() {
    	var titleBar = div("form-title");
    	titleBar.className = "form-title";
    	titleBar.innerHTML = this.options.title;
    	this.canvas.appendChild(titleBar);
    }
    
    Form.prototype.drawBody = function() {
    	var body = div("form-body");
    	body.className = "form-body";
    	this.canvas.appendChild(body);
    
    	for (var i = 0; i < this.options.fields.length; i  ) {
    		var field = this.options.fields[i];
    		var row = div();
    		var label = tag("label");
    		label.className = "form-body-label";
    		label.innerHTML = field.label;
    		label.htmlFor = field.id;
    		var fieldContainer = div();
    		fieldContainer.className = "form-body-field-container";
    		var input;
    		if (field.type == "input") {
    			input = tag("input");
    			input.type = "text";
    			input.className = "form-body-field-input";
    			input.size = field.size;
    		} else if (field.type == "checkbox") {
    			input = tag("input");
    			input.type = "checkbox";
    			input.className = "form-body-field-checkbox";
    			input.checked = field.checked ? "checked" : "";
    		} else if (field.type == "select") {
    			input = tag("select");
    			input.className = "form-body-field-select";
    		}
    		if (field.width) {
    			input.style.width = field.width;
    		}
    		input.id = field.id;
    		fieldContainer.appendChild(input);
    		row.appendChild(label);
    		row.appendChild(fieldContainer);
    		body.appendChild(row);
    	}
    
    	var buttonsRow = div();
    	buttonsRow.className = "form-body-buttons";
    	body.appendChild(buttonsRow);
    	for (var i = 0; i < this.options.buttons.length; i  ) {
    		var config = this.options.buttons[i];
    		var button = tag("input");
    		button.type = config.type;
    		button.value = config.label;
    		button.onclick = config.onclick;
    		buttonsRow.appendChild(button);
    	}
    
    }
    

    Y finalmente la implementacion, hay que recordar que este codigo se tiene que ejecutar DESPUES del que la pagina ha sido cargada, digamos, en el evento ONLOAD del window.

    window.onload = init;
    function init() {
    var config = {
    	title: "Mi nuevo formtirijillo",
    	width: "400px",
    	buttons: [{type: "submit", label: "Guardar", onclick: save} ,
    	  { type: "button", label: "Cancelar", onclick: cancel} ],
    	layout: "vertical",
    			fields: [
    				 {id: "custId", type: "input", size: "40", label: "Cliente" },
    				 {id: "address", type: "input", size: "44", label: "Direccion" },
    				 {id: "typex", type: "select", width: "124px", label: "Tipo" },
    				 {id: "loyal", type: "checkbox", label: "Es mudo?", checked: 1 }
    								]
    	};
    	var form = new Form("theform", config);
    }
    function save() {
      alert("save");
    }
    
    function cancel() {
      alert("cancel");
    }
    

    Y ultimo de todo el codigo html que necesitamos.

    <div id="theform"></div>
    

Leave a comment