Last active
May 14, 2022 22:53
-
-
Save Klerith/a42870b450f85613ed3f to your computer and use it in GitHub Desktop.
JavaScript: Varias Funciones Utiles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Inicializar tabla usando jQuery data tables | |
* en español | |
*/ | |
function init_datatable(id){ | |
$('#' + id ).dataTable( { | |
"aaSorting": [], //[[ 0, "desc" ]] | |
"oLanguage":{ | |
"infoFiltered": "(filtered from _MAX_ total records)", | |
"sProcessing": "Procesando...", | |
"sLengthMenu": "Mostrar _MENU_ registros", | |
"sZeroRecords": "No se encontraron resultados", | |
"sEmptyTable": "Ningún dato disponible en esta tabla", | |
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros", | |
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros", | |
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)", | |
"sInfoPostFix": "", | |
"sSearch": "Buscar:", | |
"sUrl": "", | |
"sInfoThousands": ",", | |
"sLoadingRecords": "Cargando...", | |
"oPaginate": { | |
"sFirst": "Primero", | |
"sLast": "Último", | |
"sNext": "Siguiente", | |
"sPrevious": "Anterior" | |
}, | |
"oAria": { | |
"sSortAscending": ": Activar para ordenar la columna de manera ascendente", | |
"sSortDescending": ": Activar para ordenar la columna de manera descendente" | |
} | |
} | |
} ); | |
} | |
/** | |
* Reemplaza todas las ocurrencias de un texto | |
*/ | |
function replaceAll(string, find, replace) { | |
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace); | |
} | |
/** | |
* Retorna un arreglo de días | |
* @return {array} arreglo con 31 dias | |
*/ | |
function getDiasArray(){ | |
return [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]; | |
} | |
/** | |
* Retorna un arreglo con los meses y el numero | |
* @return {array} arreglo con el valor :mes y nombre del mes :nombre | |
*/ | |
function getMesesArray(){ | |
return [{"mes":1, "nombre": "Enero"},{"mes":2, "nombre": "Febrero"},{"mes":3, "nombre": "Marzo"},{"mes":4, "nombre": "Abril"},{"mes":5, "nombre": "Mayo"},{"mes":6, "nombre": "Junio"},{"mes":7, "nombre": "Julio"},{"mes":8, "nombre": "Agosto"},{"mes":9, "nombre": "Septiembre"},{"mes":10, "nombre": "Octubre"},{"mes":11, "nombre": "Noviembre"},{"mes":12, "nombre": "Diciembre"}]; | |
} | |
/** | |
* Obtiene un arreglo con años a partir del numero ingresado a la fecha | |
* @param {integer} pAnioInicio ej: 2010 | |
* @return {array} | |
*/ | |
function getAniosArray(pAnioInicio){ | |
var Hoy = new Date(); | |
var Anios = []; | |
for( i = pAnioInicio; i<= Hoy.getFullYear(); i++ ){ | |
Anios.push(i); | |
} | |
return Anios; | |
} | |
/** | |
* Convierte un formulario en un jSon Perfecto | |
* @param {$("#form")} $form un formulario usando jQuery | |
* @return {jSon} Retorna un jSon con los valores de los campos listos para ser usados | |
*/ | |
function getFormData($form){ | |
var unindexed_array = $form.serializeArray(); | |
var indexed_array = {}; | |
$.map(unindexed_array, function(n, i){ | |
indexed_array[n['name']] = n['value']; | |
}); | |
return indexed_array; | |
} | |
/** | |
* Lee los parametros de URL | |
* ej: QueryString.identidad | |
* eso regresaria el valor de un parametro via URL llamado identidad. | |
*/ | |
var QueryString = function () { | |
var query_string = {}; | |
var query = window.location.search.substring(1); | |
var vars = query.split("&"); | |
for (var i=0;i<vars.length;i++) { | |
var pair = vars[i].split("="); | |
// If first entry with this name | |
if (typeof query_string[pair[0]] === "undefined") { | |
query_string[pair[0]] = pair[1]; | |
// If second entry with this name | |
} else if (typeof query_string[pair[0]] === "string") { | |
var arr = [ query_string[pair[0]], pair[1] ]; | |
query_string[pair[0]] = arr; | |
// If third or later entry with this name | |
} else { | |
query_string[pair[0]].push(pair[1]); | |
} | |
} | |
return query_string; | |
} (); | |
/** | |
* Bloquea todos los input,select,button,textarea | |
*/ | |
function Bloquear(){ | |
$("input,select,button,textarea").attr("disabled","disabled"); | |
} | |
/** | |
* DesBloquea todos los input,select,button,textarea | |
*/ | |
function DesBloquear(){ | |
$("input,select,button,textarea").removeAttr("disabled"); | |
} | |
/** | |
* Llama el MetroNotification SmallBox con forma de error | |
* @param {string} titulo | |
* @param {string} mensaje | |
* @return {nothing} esta funcion no regresa nada. | |
*/ | |
function msgError(titulo, mensaje){ | |
$.smallBox({title: titulo,content: mensaje,color: '#ed145b',timeout: '5000', sound:false}); | |
} | |
/** | |
* Llama el MetroNotification SmallBox con forma de notificacion normal | |
* @param {string} titulo | |
* @param {string} mensaje | |
* @return {nothing} esta funcion no regresa nada. | |
*/ | |
function msgOk(titulo,mensaje){ | |
$.smallBox({title: titulo,content: mensaje, color: '#662d91',timeout: '5000', sound:false}); | |
} | |
/** | |
* Retorna un el numero formateado a moneda | |
* @param {double or integer} Monto | |
* @param {string} Simbolo de la moneda | |
*/ | |
function numeroAMoneda(Monto, Simbolo){ | |
if(Simbolo == undefined ) | |
return "L. " + Monto.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); | |
else | |
return Simbolo + ". " + Monto.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); | |
} | |
/** | |
* Crea mascaras por defecto en los campos que tengan esas clases | |
* @return {nothing} No retorna nada | |
*/ | |
$(document).ready(function () { | |
$(".telefono").each(function(){ | |
$(this).attr("data-mask","9999-9999"); | |
}); | |
$(".identidad").each(function(){ | |
$(this).attr("data-mask","9999-9999-99999"); | |
}); | |
$(".patrono").each(function(){ | |
$(this).attr("data-mask","999-9999-9999-*"); | |
}); | |
$(".fecha").each(function(){ | |
$(this).attr("data-mask","99/99/9999"); | |
}); | |
// Hace que el control con la clase "solonumeros" admita solo numeros del teclado | |
/** | |
* Bloquea que el campo solo | |
* Allow: backspace, delete, tab, escape, enter and . | |
*/ | |
$("body").on("keydown",".solonumeros",function (e) { | |
if(e.keyCode == 109){ | |
$(this).val(""); | |
$(this).focus(); | |
} | |
var ValorActual = $(this).val(); | |
if( ValorActual.indexOf(".")>0 && e.keyCode==190){ | |
e.preventDefault(); | |
return; | |
}; | |
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190,110]) !== -1 || | |
// Allow: Ctrl+A | |
(e.keyCode == 65 && e.ctrlKey === true) || | |
// Allow: home, end, left, right | |
(e.keyCode >= 35 && e.keyCode <= 39)) { | |
// let it happen, don't do anything | |
return; | |
} | |
// Ensure that it is a number and stop the keypress | |
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { | |
e.preventDefault(); | |
} | |
}); | |
}); | |
/** | |
* Valida si la fecha es valida | |
* Recibe una fecha con formato 01/01/2004 y devuelve si es una fecha correcta o no. | |
* @return {boolean} true, false | |
*/ | |
function esFechaCorrecta (fecha) { | |
var arrayFecha = fecha.split("/"); | |
//Comprobamos que se tengan 3 datos (dia, mes y año) no vacios | |
if (arrayFecha.length!=3 || arrayFecha[0]=="" || arrayFecha[1]=="" || arrayFecha[2]=="") | |
return false; | |
var anyo = parseInt(quitaCeros(arrayFecha[2])); | |
//Devuelve el mes numérico o null | |
var mes = devuelveMes(quitaCeros(arrayFecha[1])); | |
var dia = parseInt(quitaCeros(arrayFecha[0])); | |
//------------------------------------- | |
//Comprobamos que los valores son numéricos | |
if (isNaN(anyo) || isNaN(mes) || isNaN(dia)) | |
return false; | |
//Comprobamos valores correctos de dia mes y anyo | |
if (dia<1 || dia>31 || mes<1 || mes>12 || anyo<0) | |
return false; | |
//Comprobamos meses de 30 dias | |
if ((mes==4 || mes==6 || mes==9 || mes==11) && dia>30) | |
return false; | |
//Comprobamos mes febrero & bisiestos | |
if (mes==2 && (dia > 29 || (dia==29 && ((anyo%400!=0) && ((anyo%4!=0) || (anyo%100==0)))) )) | |
return false; | |
return true; | |
} | |
/** | |
* Valida una fecha con dias, meses y años separados | |
* @param {integer} day | |
* @param {integer} month | |
* @param {integer} year | |
* @return {Boolean} | |
*/ | |
function isValidDate(day,month,year) | |
{ | |
var dteDate; | |
month=month-1; | |
dteDate=new Date(year,month,day); | |
//Devuelva true o false... | |
return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear())); | |
} | |
/* | |
/** | |
* Quita los ceros del principio de una cadena si tiene (01)->(1) | |
* @param {string} | |
* @return {double} | |
*/ | |
function quitaCeros(cad){ | |
var enc = false; | |
var i=0; | |
while (i<cad.length && !enc) { | |
if (cad.charAt(i)=='0'){ | |
i++; | |
} else{ | |
enc = true; | |
} | |
} | |
return (cad.substring(i,cad.length)*1); | |
} | |
/** | |
* Retorna la edad de la persona | |
* La fecha tiene que tener el formato de dd/mm/yyyy | |
* @param {date} fecha | |
* @return {integer} | |
*/ | |
function calcularEdad(fecha) | |
{ | |
if(validate_fecha(fecha)==true) | |
{ | |
// Si la fecha es correcta, calculamos la edad | |
var values=fecha.split("/"); | |
var dia = values[2]; | |
var mes = values[1]; | |
var ano = values[0]; | |
// cogemos los valores actuales | |
var fecha_hoy = new Date(); | |
var ahora_ano = fecha_hoy.getYear(); | |
var ahora_mes = fecha_hoy.getMonth(); | |
var ahora_dia = fecha_hoy.getDate(); | |
// realizamos el calculo | |
var edad = (ahora_ano + 1900) - ano; | |
if ( ahora_mes < (mes - 1)) | |
{ | |
edad--; | |
} | |
if (((mes - 1) == ahora_mes) && (ahora_dia < dia)) | |
{ | |
edad--; | |
} | |
if (edad > 1900) | |
{ | |
edad -= 1900; | |
} | |
return(edad); | |
}else{ | |
return -1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Funciones incluidas: