Skip to content

Instantly share code, notes, and snippets.

@hrbullon
Last active September 23, 2019 13:46
Show Gist options
  • Save hrbullon/f526402bb9b39bc23c71f14f032a3ae1 to your computer and use it in GitHub Desktop.
Save hrbullon/f526402bb9b39bc23c71f14f032a3ae1 to your computer and use it in GitHub Desktop.
Utils Javascript Functions
/**
* This functions is for ajax error handling
* Now it can captch these erroCode 0,400,403,404 y 500, so you can add more an more status code
*/
$(function() {
//Setup ajax error handling
$.ajaxSetup({
data: {
'csrf_tkn': $("[name='csrf_tkn']").val()//If you have a token that you need to send in each one requests
},
beforeSend: function() {
//Pace.restart();
if (!navigator.onLine) {
alert("Verifique su conexión a internet");
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status === 0) {
alert('Not connect: Verify Network.');
} else if (jqXHR.status == 400) {
alert('Bad Request [400]');
} else if (jqXHR.status == 403) {
alert("Sorry, your session has expired. Please login again to continue");
} else if (jqXHR.status == 404) {
alert('Requested page not found [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (textStatus === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (textStatus === 'timeout') {
alert('Time out error.');
} else if (textStatus === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error: ' + jqXHR.responseText);
}
}
});
});
/**
* This functions is validated to use in Venezuela,
* But you may modify to be used in other input.
* So this function apply automatically a format like this J-00000000
* Because this is the format for a RIF (Registro de Información Fiscal)
*/
function HandleInputFiscal {
if ($(".input-fiscal").length > 0) {
$(".input-fiscal").on({
"focus": function(event) {
$(event.target).select();
},
"keyup": function(event) {
$(event.target).val(function(index, value) {
//Remove blank space
var value = value.replace(/(\s+)/, "");
//Substract first character
var first_str = value.substr(0, 1);
//Substract rest characters
var rest_str = value.substr(1);
//Replace any character
rest_str = rest_str.replace(/\D/g, "");
if (first_str !== "" || rest_str !== "") {
if (/[v|V|e|E|j|J|g|G]/.test(first_str)) {
if (rest_str !== "") {
return first_str.toUpperCase() + "-" + rest_str.substr(0, 9);
} else {
return first_str.toUpperCase();
}
} else {
return "";
}
} else {
return "";
}
});
}
});
}
}
/**
* This functions apply automatically a format like this $100.00 OR $100,00
*/
function HandleInputAmount {
$(".input-amount").on({
"focus": function(event) {
$(event.target).select();
},
"keyup": function(event) {
//Quantity of decimals do you want to has the number
var decimal_number = 2;
//Char to separate thousands
var thousands_separator = ",";//Usually when thousands_separator is ="," then decimals separator is "."
$(event.target).val(function(index, value) {
return value.replace(/\D/g, "")
.replace(/([0-9])([0-9]{2})$/, '$1.$2')//The point between $1 and $2 may replaced for ","
.replace(/\B(?=(\d{3})+(?!\d)\.?)/g, thousands_separator);
});
}
});
}
/**
*
* Generate a DatePicker this function required Datepicker.js
* It is a jquery plugins
*/
function HandleInputDatePicker() {
if ($(".input-date").length > 0) {
//Init datepicker
$(".input-date").datepicker({
todayHighlight: true,//Choose today by default
autoclose: true,//Close after choose option
language: 'es',//Define language
format: 'dd/mm/yyyy' //Format to show date 01/01/2019
});
}
}
/**
* This function verify if key pressed is different to number
* So this function just allow write numbers
*/
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
/**
* Convert a data form in a data JSON
* @param {$("#form")} $form a form using JQUERY
* @return {jSon} Retorn a json with values of fields ready to be used
*/
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;
}
document.getElementById("file").onchange = function(e) {
// Creamos el objeto de la clase FileReader
let reader = new FileReader();
// Leemos el archivo subido y se lo pasamos a nuestro fileReader
reader.readAsDataURL(e.target.files[0]);
// Le decimos que cuando este listo ejecute el código interno
reader.onload = function(){
let preview = document.getElementById('preview'),
image = document.createElement('img');
image.src = reader.result;
preview.innerHTML = '';
preview.append(image);
};
}
@hrbullon
Copy link
Author

Included Functions

  • HandleInputFiscal
  • HandleInputAmount
  • HandleInputDatePicker
  • isNumberKey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment