<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
input {padding:20px;margin:10px;font-size:18px;}
.number {text-align:right;}
</style>
</head>
<body>
<div><input type="text" class="number"></div>
<div><input type="text" class="number"></div>
</body>
</html>
<script>
// Creamos el evento keyup
document.querySelectorAll(".number").forEach(el => el.addEventListener("keyup", numberFormat));
// Función que formatea el numero
function numberFormat(e) {
if (this.value=="") {
return;
}
// Obtenemos un array con el numero y los decimales si hay
let contenido = this.value.replace(/[^0-9\.]/g, "").split(".");
// añadimos los separadores de miles al primer numero del array
contenido[0] = contenido[0].length ? new Intl.NumberFormat('en-US').format(parseInt(contenido[0])) : "0";
// Juntamos el numero con los decimales si hay decimales
this.value=contenido.length>1 ? contenido.slice(0, 2).join(".") : contenido[0];
}
</script>
Comentarios sobre la versión: Solo numeros positivos (0)
No hay comentarios