Skip to content

Instantly share code, notes, and snippets.

@rickycheers
Created January 28, 2013 22:56
Show Gist options
  • Save rickycheers/4660074 to your computer and use it in GitHub Desktop.
Save rickycheers/4660074 to your computer and use it in GitHub Desktop.
Callback implementation for only allowing the insertion of numbers on an input.
$('#selector').on('keydown', onlyNumber);
function onlyNumber(event){
// Allow: backspace, delete, tab, escape, and enter
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39) ||
// Allow point
(event.keyCode == 190)
) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
}
@EdwinBetanc0urt
Copy link

Con jQuery

//validaciones para valores NUMERICOS
$('.valida_numerico').keyup(function() {
    this.value = this.value.replace(/[^0-9]/g, '');
});

Con JavaScript

let elementosDOM = document.querySelectorAll('.valida_num_entero');
//Recorremos cada uno de nuestros elementos HTML

elementosDOM.forEach(elemento => {
    elemento.addEventListener('keyup', function() {   
        this.value = this.value.replace(/[^0-9]/g, '');
    });
});

ejemplo:

<input class="valida_numerico" />

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