Ver Mensaje Individual
  #129 (permalink)  
Antiguo 06/05/2003, 15:22
Avatar de Kaopectate
Kaopectate
Colaborador
 
Fecha de Ingreso: diciembre-2001
Ubicación: Curaçao (Antillas Holandesas)
Mensajes: 3.179
Antigüedad: 24 años, 8 meses
Puntos: 38
131.- Validar la entrada de un campo numérico y dar formato al resultado

P: ¿Como puedo hacer una entrada de datos donde se valide el ingreso de caracteres numéricos o los signos ",.-" y que al salir del mismo aparezca el resultado con decimales y formato para los miles?

Créditos: Mackpipe

R: [ver ejemplo]

Código PHP:
<html>
 <
head>
  <
script>
   function 
NumberFormat(num, numDec, decSep, thousandSep){
    var 
arg;
    var 
Dec;
    
Dec = Math.pow(10, numDec); 
    if (
typeof(num) == 'undefined') return; 
    if (
typeof(decSep) == 'undefined') decSep = ',';
    if (
typeof(thousandSep) == 'undefined') thousandSep = '.';
    if (
thousandSep == '.')
     
arg=/./g;
    else
     if (
thousandSep == ',') arg=/,/g;
    if (
typeof(arg) != 'undefined') num = num.toString().replace(arg,'');
    
num = num.toString().replace(/,/g, '.'); 
    if (
isNaN(num)) num = "0";
    
sign = (num == (num = Math.abs(num)));
    
num = Math.floor(num * Dec + 0.50000000001);
    
cents = num % Dec;
    
num = Math.floor(num/Dec).toString(); 
    if (
cents < (Dec / 10)) cents = "0" + cents; 
    for (var 
i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
     
num = num.substring(0, num.length - (4 * i + 3)) + thousandSep + num.substring(num.length - (4 * i + 3));
    if (
Dec == 1)
     return (((
sign)? '': '-') + num);
    else
     return (((
sign)? '': '-') + num + decSep + cents);
   } 

   function 
EvaluateText(cadena, obj){
    
opc = false; 
    if (
cadena == "%d")
     if (
event.keyCode > 47 && event.keyCode < 58)
      
opc = true;
    if (
cadena == "%f"){ 
     if (
event.keyCode > 47 && event.keyCode < 58)
      
opc = true;
     if (
obj.value.search("[.*]") == -1 && obj.value.length != 0)
      if (
event.keyCode == 46)
       
opc = true;
    }
    if(
opc == false)
     
event.returnValue = false; 
   }
  
</script>
 </head>
 <body>
  <form name="frm">
   numero
   <input type="text" name="input1" size="15" value="500034567" onkeypress="EvaluateText('%f', this);" onBlur="this.value = NumberFormat(this.value, '2', '.', ',')"><br><br>
  </form>
 </body>
</html> 

Última edición por Kaopectate; 07/05/2003 a las 11:44