Hola chicos, intento que pueda ingresar números con mi teclado en un campo de número html del 1 al 100.
Tomé la función de aquí Entrada de número HTML min y max no funciona correctamente y funcionó correctamente para números entre 1-100.
Pero aun puedo ingresar letras y no se como solucionarlo. Traté de agregar
if (typeof (parseInt(el.value)) != 'number') { el.value = el.min; }Pero no está funcionando. Aquí está mi código completo:
const enforceMinMax = (el) => { if (el.value != "") { if (parseInt(el.value) < parseInt(el.min)) { el.value = el.min; } if (parseInt(el.value) > parseInt(el.max)) { el.value = el.max; } if (typeof (parseInt(el.value)) != 'number') { el.value = el.min; } } } <input type="number" id="quantity" name="quantity" min="1" max="100" step="1" onkeyup=enforceMinMax(this) ><br /><br />¿Cómo puedo dejar de ingresar letras con mi teclado en un campo de número html?
Podría aplicar esta misma lógica a cada entrada numérica que tenga un atributo mínimo y máximo como este:
// find all numeric inputs that have both min & max attributes // and apply the event handler to each. document.querySelectorAll('input[type="number"][min][max]').forEach( input => input.addEventListener('keyup', function(e) { // if the value is numeric proceed - test the numeric value of the input against the min/max attribute values. if( !isNaN( Number( this.value ) ) ) { if( Number( this.value ) > this.max )this.value=this.max; if( Number( this.value ) < this.min )this.value=this.min; return true; } e.preventDefault(); return false; }) ); <input type="number" name="quantity" min="1" max="100" step="1" />Puede comparar keyCode y devolver falso si la clave no es un número, luego, al activar la tecla, puede validar el valor mínimo y máximo, en consecuencia modificar el valor de entrada
<!DOCTYPE html> <html> <head> <title>Parcel Sandbox</title> <meta charset="UTF-8" /> <script> function handleKeyDown(e) { if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { e.preventDefault(); return false; } } function handleKeyUp(e) { const v = e?.target?.value || 0; if (parseInt(v) === NaN || parseInt(v) < 1) { e.target.value = 1; } else if (parseInt(v) > 100) { e.target.value = 100; } } </script> </head> <body> <input type="number" min="1" max="100" onkeydown="handleKeyDown(event)" onkeyup="handleKeyUp(event)" /> </body> </html>