forms.js 2.2 KB
"use strict";

function collectToSearch() {
	const f = document.getElementById("form");
	const inputs = f.getElementsByTagName("input");
	const defecto = document.getElementsByName("defecto")[0].value;

	let data = {};

	function BadInputException(input) {
		this.error = "badinput";
		this.input = input;
	}

	Array.from(inputs).forEach( input => {

		if (input.checkValidity() === false){
			input.reportValidity("Por favor llene este campo");
			throw BadInputException(input);
		}

		const sub = input.getAttribute("sub");
		if ( (sub in data) === false ) {
			data[sub] = {}
		}
		data[sub][input.name] = (input.value === "" ? defecto : input.value);
	});

	message("Espere...");
	
	const obj = {
		"url" : "/pdf",
		"contentType" : "application/json",
		"async" : true,
		"data" : data,
		"success" : (response) => {
			let r;
			try {
				r = JSON.parse(response);
				document.getElementById("message").click();
			} catch (error) {
				message(response);
			}
			document.getElementById("results").style.display = "block";
			document.getElementById("form").style.display = "none";
			fillResults(r);
		},
		"error" : (response) => message(response),
		"timeout" : 120000,
		"ontimeout" : (response) => message("La conexión tardó demasiado.")
	}
	
	let ajax = new Ajax(obj);
	ajax.post();
}

function collectToConvert() {
	const r = document.getElementById("results")
	const inputs = r.getElementsByTagName("input");

	let data = {};
	const defecto = document.getElementsByName("defecto")[0].value;

	Array.from(inputs).forEach(input => {
		if (input.name == "defecto") return;

		const sub = input.getAttribute("sub");
		if ((sub in data) === false) {
			data[sub] = {}
		}
		data[sub][input.name] = (input.value == "?" || input.value == "" ? defecto : input.value);
	});

	return data;
}

function message(msg) {
	let m = document.getElementById("message");
	m.style.display = "block";
	m = document.getElementById("msg");
	m.innerHTML = msg;
}

function fillResults(results) {
	const r = document.getElementById("results")
	const inputs = r.getElementsByTagName("input");

	Array.from(inputs).forEach(input => {
		if (input.name == "defecto") return;

		const sub = input.getAttribute("sub");
		input.value = results[sub][input.name];
	});
}