type only number length float html html5 input numbers max

only - ¿Cómo puedo limitar las entradas posibles en un elemento de "número" de HTML5?



input type number min (22)

Al igual que con type="number" , usted especifica una propiedad max lugar de maxlength , que es el número máximo posible. Entonces, con 4 dígitos, el max debe ser 9999 , 5 dígitos 99999 y así sucesivamente.

Además, si desea asegurarse de que sea un número positivo, puede establecer min="0" , asegurando números positivos.

Para el elemento <input type="number"> , maxlength no funciona. ¿Cómo puedo restringir la maxlength para ese elemento numérico?


Como descubrí, no puede usar ninguno de onkeyup eventos onkeydown , onkeypress o onkeyup para una solución completa, incluidos los navegadores móviles. Por cierto, onkeypress está obsoleto y ya no está presente en chrome / opera para Android (consulte: Borrador de trabajo de W3C del UI Events, 4 de agosto de 2016 ).

Encontré una solución usando el evento oninput solamente. Es posible que tenga que hacer una verificación de números adicional según sea necesario, como el signo negativo / positivo o decimales y separadores de miles y similares, pero como comienzo debería bastar con lo siguiente:

function checkMaxLength(event) { // Prepare to restore the previous value. if (this.oldValue === undefined) { this.oldValue = this.defaultValue; } if (this.value.length > this.maxLength) { // Set back to the previous value. this.value = oldVal; } else { // Store the previous value. this.oldValue = this.value; // Make additional checks for +/- or ./, etc. // Also consider to combine ''maxlength'' // with ''min'' and ''max'' to prevent wrong submits. } }

También recomendaría combinar maxlength con min y max para evitar maxlength incorrectos como se indicó anteriormente varias veces.


Como lo han dicho otros, min / max no es lo mismo que maxlength porque las personas aún podrían ingresar un flotante que sería más grande que la longitud máxima de la cadena que pretendía. Para emular realmente el atributo maxlength, puedes hacer algo como esto en un pellizco (esto es equivalente a maxlength = "16"):

<input type="number" oninput="if(value.length>16)value=value.slice(0,16)">


Entrada HTML

<input class="minutesInput" type="number" min="10" max="120" value="" />

jQuery

$(".minutesInput").on(''keyup keypress blur change'', function(e) { if($(this).val() > 120){ $(this).val(''120''); return false; } });


La longitud máxima no funcionará con <input type="number" la mejor manera que conozco es usar el evento oninput para limitar la longitud máxima. Por favor vea el código de abajo para una implementación simple.

<input name="somename" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type = "number" maxlength = "6" />


La respuesta de Maycow Moura fue un buen comienzo. Sin embargo, su solución significa que cuando ingresa el segundo dígito, se detiene toda la edición del campo. Así que no puedes cambiar valores ni borrar ningún carácter.

El siguiente código se detiene en 2, pero permite continuar con la edición;

//MaxLength 2 onKeyDown="if(this.value.length==2) this.value = this.value.slice(0, - 1);"


Los atributos más relevantes para usar serían min y max .


O si su valor máximo es, por ejemplo, 99 y mínimo 0, puede agregarlo al elemento de entrada (su valor será reescrito por su valor máximo, etc.)

<input type="number" min="0" max="99" onKeyUp="if(this.value>99){this.value=''99'';}else if(this.value<0){this.value=''0'';}" id="yourid">

Luego (si lo desea), puede verificar si el ingreso es realmente el número


Otra opción es simplemente agregar un escucha para cualquier cosa con el atributo maxlength y agregar el valor de la porción a eso. Suponiendo que el usuario no quiera usar una función dentro de cada evento relacionado con la entrada. Aquí hay un fragmento de código. Ignora el código CSS y HTML, lo que importa es JavaScript.

// Reusable Function to Enforce MaxLength function enforce_maxlength(event) { var t = event.target; if (t.hasAttribute(''maxlength'')) { t.value = t.value.slice(0, t.getAttribute(''maxlength'')); } } // Global Listener for anything with an maxlength attribute. // I put the listener on the body, put it on whatever. document.body.addEventListener(''input'', enforce_maxlength);

label { margin: 10px; font-size: 16px; display: block } input { margin: 0 10px 10px; padding: 5px; font-size: 24px; width: 100px } span { margin: 0 10px 10px; display: block; font-size: 12px; color: #666 }

<label for="test_input">Text Input</label> <input id="test_input" type="text" maxlength="5"/> <span>set to 5 maxlength</span> <br> <label for="test_input">Number Input</label> <input id="test_input" type="number" min="0" max="99" maxlength="2"/> <span>set to 2 maxlength, min 0 and max 99</span>


Para quien busca una limitación global como yo:

$(document).on(''keypress'',''input[type="number"][maxlength]'', function(){ return this.value.length < +this.attributes.maxlength.value; });

Esto atrapa cada pulsación de tecla en el documento y lo filtra si la entrada es una entrada de "número" y tiene un atributo de maxlength . Luego permite la tecla presionada cuando la longitud no alcanzó la longitud máxima. También funciona con entradas y modales agregados dinámicamente, etc.


Puede especificar los atributos min y max , lo que permitirá la entrada solo dentro de un rango específico.

<!-- equivalent to maxlength=4 --> <input type="number" min="-9999" max="9999">

Sin embargo, esto solo funciona para los botones de control de giro. Aunque el usuario puede escribir un número mayor que el max permitido, el formulario no se enviará.


Captura de pantalla tomada de Chrome 15

Puede usar el evento HTML5 oninput en JavaScript para limitar el número de caracteres:

myInput.oninput = function () { if (this.value.length > 4) { this.value = this.value.slice(0,4); } }


Puede especificarlo como texto, pero agregue Pettern, que solo coincida con los números:

<input type="text" pattern="/d*" maxlength="2">

Funciona perfectamente y también en el móvil (probado en iOS 8 y Android) saca el teclado numérico.


Puedes combinar todo esto así:

<input name="myinput_drs" oninput="maxLengthCheck(this)" type = "number" maxlength = "3" min = "1" max = "999" /> <script> // This is an old version, for a more recent version look at // https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/ function maxLengthCheck(object) { if (object.value.length > object.maxLength) object.value = object.value.slice(0, object.maxLength) } </script>


Actualizar:
También es posible que desee evitar que se object.length caracteres no numéricos, porque object.length sería una cadena vacía para las entradas de números y, por lo tanto, su longitud sería 0 . Por lo tanto, la función maxLengthCheck no funcionará.

Solución:
Vea this o this para ejemplos.

Demo - Vea la versión completa del código aquí:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

Actualización 2: Aquí está el código de actualización: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

Actualización 3: Tenga en cuenta que permitir que se ingrese más de un punto decimal puede desordenar el valor numérico.


Puedes probar esto también para la entrada numérica con restricción de longitud

<input type="tel" maxlength="3" />


Sé que ya hay una respuesta, pero si desea que su entrada se comporte exactamente como el atributo maxlength o lo más cerca posible, use el siguiente código:

(function($) { methods = { /* * addMax will take the applied element and add a javascript behavior * that will set the max length */ addMax: function() { // set variables var maxlAttr = $(this).attr("maxlength"), maxAttR = $(this).attr("max"), x = 0, max = ""; // If the element has maxlength apply the code. if (typeof maxlAttr !== typeof undefined && maxlAttr !== false) { // create a max equivelant if (typeof maxlAttr !== typeof undefined && maxlAttr !== false){ while (x < maxlAttr) { max += "9"; x++; } maxAttR = max; } // Permissible Keys that can be used while the input has reached maxlength var keys = [ 8, // backspace 9, // tab 13, // enter 46, // delete 37, 39, 38, 40 // arrow keys<^>v ] // Apply changes to element $(this) .attr("max", maxAttR) //add existing max or new max .keydown(function(event) { // restrict key press on length reached unless key being used is in keys array or there is highlighted text if ($(this).val().length == maxlAttr && $.inArray(event.which, keys) == -1 && methods.isTextSelected() == false) return false; });; } }, /* * isTextSelected returns true if there is a selection on the page. * This is so that if the user selects text and then presses a number * it will behave as normal by replacing the selection with the value * of the key pressed. */ isTextSelected: function() { // set text variable text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return (text.length > 0); } }; $.maxlengthNumber = function(){ // Get all number inputs that have maxlength methods.addMax.call($("input[type=number]")); } })($) // Apply it: $.maxlengthNumber();


Si está buscando una solución de Web móvil en la que desee que su usuario vea un teclado numérico en lugar de un teclado de texto completo. Utilice type = "tel". Funcionará con maxlength, lo que le ahorra la creación de javascript extra.

Max y Min seguirán permitiendo que el usuario escriba números en exceso de max y min, lo que no es óptimo.


Tuve este problema antes y lo resolví usando una combinación de tipo de número html5 y jQuery.

<input maxlength="2" min="0" max="59" name="minutes" value="0" type="number"/>

guión:

$("input[name=''minutes'']").on(''keyup keypress blur change'', function(e) { //return false if not 0-9 if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; }else{ //limit length but allow backspace so that you can still delete the numbers. if( $(this).val().length >= parseInt($(this).attr(''maxlength'')) && (e.which != 8 && e.which != 0)){ return false; } } });

No sé si los eventos son un poco excesivos, pero resolvieron mi problema. JSfiddle


Ugh. Es como si alguien se rindiera a mitad de la implementación y pensara que nadie se daría cuenta.

Por la razón que sea, las respuestas anteriores no utilizan los atributos min y max . Este jQuery lo termina:

$(''input[type="number"]'').on(''input change keyup paste'', function () { if (this.min) this.value = Math.max(parseInt(this.min), parseInt(this.value)); if (this.max) this.value = Math.min(parseInt(this.max), parseInt(this.value)); });

Probablemente también funcionaría como una función con nombre "oninput" w / o jQuery si uno de esos tipos "jQuery-is-the-devil".


Una forma sencilla de establecer maxlength para entradas numéricas es:

<input type="number" onkeypress="if(this.value.length>=4) { return false;}" oninput="if(this.value.length>=4) { this.value = this.value.slice(0,4); }" />


Y puede agregar un atributo max que especificará el número más alto posible que puede insertar

<input type="number" max="999" />

Si agrega tanto un valor max como uno min , puede especificar el rango de valores permitidos:

<input type="number" min="1" max="999" />

Lo anterior aún no impedirá que un usuario ingrese manualmente un valor fuera del rango especificado. En su lugar, se mostrará una ventana emergente que le indicará que ingrese un valor dentro de este rango al enviar el formulario como se muestra en esta captura de pantalla:


es muy simple, con algunos javascript puedes simular un maxlength , échale un vistazo:

//maxlength="2" <input type="number" onKeyDown="if(this.value.length==2) return false;" />


//For Angular I have attached following snippet.

<div ng-app=""> <form> Enter number: <input type="number" ng-model="number" onKeyPress="if(this.value.length==7) return false;" min="0"> </form> <h1>You entered: {{number}}</h1> </div>

Si usa el evento "onkeypress", no obtendrá ninguna limitación del usuario como tal durante el desarrollo (prueba de la unidad). Y si tiene un requisito que no le permita al usuario ingresar después de un límite particular, mire este código e inténtelo una vez.