Foro de elhacker.net

Programación => Desarrollo Web => Mensaje iniciado por: OssoH en 27 Septiembre 2013, 13:34 pm



Título: input con tres decimales. javascript
Publicado por: OssoH en 27 Septiembre 2013, 13:34 pm
Hola :
Tengo un campo edit y quiero establecer una máscara para que me permita introducir tantos enteros como desee y sólo tres decimales.

Tengo el siguiente codigo
Código:
<script>
function NumCheck(e, field) {
key = e.keyCode ? e.keyCode : e.which

// backspace
if (key == 8) return true
// 0-9
if (key > 47 && key < 58) {
if (field.value == "") return true
//return field.value.toFixed(2);
regexp = /.[0-9]{3}$/
return !(regexp.test(field.value))
}
// .
if (key == 46) {
if (field.value == "") return false
regexp = /^[0-9]+$/
return regexp.test(field.value)
}
// other key return false
return false;

}
</script>
<input type="text" onkeypress="return NumCheck(event, this)"/>

Si que funciona la parte decimal porque te deja poner hasta un máximo de 3 digitos, pero el problema está en la parte entera que te deja poner hasta 4 digitos máximo.
Es decir, si escribo 230090.123 no me lo permite.

Alguien sabe como arreglarlo?

Gracias de antemano!!


Título: Re: input con tres decimales. javascript
Publicado por: OssoH en 27 Septiembre 2013, 17:19 pm
nada ...sigo intentandolo. La expresión regular se me "atraganta"


Título: Re: input con tres decimales. javascript
Publicado por: OssoH en 27 Septiembre 2013, 18:08 pm
Al final lo he conseguido. Pongo la solución aunque seguramente haya una forma más fácil de hacerlo.

Código:
function onlyDotsAndNumbers(txt, event) {
    var charCode = (event.which) ? event.which : event.keyCode   
   
// backspace
if (charCode == 8) return true

if (charCode == 46) {
        if (txt.value.indexOf(".") < 0)
            return true;
        else
            return false;
    }

    if (txt.value.indexOf(".") > 0) {
        var txtlen = txt.value.length;
        var dotpos = txt.value.indexOf(".");
        if ((txtlen - dotpos) > 3)
            return false;
    }

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}