Estou com problema em um Javascript

10 respostas
D
Pessoal eu tenho o seguinte código bagunçado:
<SCRIPT language=JavaScript> 

function retiraZero(numero) { 
	novoNumero = "";
	aux = ""; 
	for(i=0;i<numero.length;i++){
		if(numero.charAt(i) == "0" || numero.charAt(i) == ",") { 
			continue; 
		}else{ 
			zeroDireita = true;
			novoNumero += numero.charAt(i); 
		}
		if(zeroDireita){
			if (numero.charAt(6) == "0"){
				novoNumero += numero.charAt(6);
			}
			if (numero.charAt(5) == "0" && numero.charAt(6)=="0"){
				novoNumero += numero.charAt(6);
			}
			if (numero.charAt(4) == "0" && numero.charAt(5)=="0" && numero.charAt(6)=="0"){
				novoNumero += numero.charAt(6);
			}
			/*if (numero.charAt(2) == "0" && numero.charAt(4) == "0" && numero.charAt(5)=="0" && numero.charAt(6)=="0"){
				novoNumero += numero.charAt(6);
			}*/
		}
	} 
	
	if(novoNumero.length == 3){ 
		novoNumero = novoNumero.charAt(0) + "," + novoNumero.substr(1,2); 
	} 
	else if(novoNumero.length == 4){ 
		novoNumero = novoNumero.substr(0,2) + "," + novoNumero.substr(2,2); 
	} 
	else if(novoNumero.length >= 5){ 
		novoNumero = novoNumero.substr(0,3) + "," + novoNumero.substr(3,6);
	} 
	return novoNumero; 
} 

function formataPorcentagem(texto){ 
	num = texto.value; 
	num = retiraZero(num); 

	if(num > 100) {
		num = 100;
	}

	if(num.length == 1) { 
		texto.value = "000,0" + num;
	} 
	if(num.length == 2) { 
		texto.value = "000," + num; 
	}
	if(num.length == 4) { 
		texto.value = "00" + num; 
	} 
	if(num.length == 5) { 
		texto.value = "0" + num;
	}
	if(num.length == 6) {
		texto.value = num; 
	}
	if (num.length == 7){
		texto.value = num.substr(0,6);
	}
} 


</script>
<INPUT onkeyup="return formataPorcentagem(this)" size=8 maxlength="7"> <br>

A ideia dele era a seguinte: de acordo com o numero que eu digitava ele ia colocando ele com duas casas decimais ou 100,00. Ex:

digitou 1 -> 00,01
digitou 2000 -> 20,00
digitou 2010 -> 20,10
digitou 10000 -> 100,00

alguem tem uma solução para resolver este problema ou simplesmente uma melhoria para o código acima?

10 Respostas

fenrir

Não testei o código, mas se ele funciona, pra que mexer?!?!?

Existe aquela máxima em programação: se algo funciona, não mexa!

D

“fenrir”:
Não testei o código, mas se ele funciona, pra que mexer?!?!?

Existe aquela máxima em programação: se algo funciona, não mexa!

Ele funciona até certo ponto! Pois se eu coloco 10,20 ele tira o zero entre o 1 e ,

cv1

Trofeu ACME pra voce :lol: - mexer sempre (e de forma correta) eh justamente o que faz a qualidade de um software aumentar. Conheca mais sobre Refactoring :wink:

louds

Trofeu ACME pra voce :lol: - mexer sempre (e de forma correta) eh justamente o que faz a qualidade de um software aumentar. Conheca mais sobre Refactoring ;)

Isso só vale quando o código te da os subsidios necessarios. Como ser compreensivel, testavel e finito.
Eu, pelo menos, não tenho coragem de tocar naqueles negocios de 8000 linhas que SDS oque faz e ate onde seus tentáculos se extendem.

Caso contrario, é aquilo que o vc falou, mexa mexa mexa e mexa mais ainda. Se não gostou só puxar a versão anterior do SCM e pronto.

_fs

Fiz uma gambiarrinha aqui, talvez ajude. Não está checando um monte de coisas, então dá uma olhada melhor.
Não entendo ainda direito o esquema de eventos em browsers nao-ie. Seria muito mais interessante o evento retornar a string correta, ao invés de substituir. Mas infelizmente um onkeydown=“return false;” não resolve nada.
Mas é um ponto de partida :smiley:

<html>
	<head>
		<title>Tests</title>
		
		<script language="javascript">
			function mask( el )
			{
				var val = el.value;
				var len = val.length;
				var f = '';
				
				// substituir por replace( ',', '' )
				val = val.substring( 0, val.indexOf( ',' ) ) + val.substring( val.indexOf( ',' ) + 1, val.length );
				
				for( var i = 0; i < len; i++ )
				{
					if( i == len - 3 )
						f += ',';
					
					if( i > 0 || val.charAt( i ) != '0' )
						f += val.charAt( i );					
				}

				el.value = f;
			}
		</script>
	</head>

	<body>
		<input type="text" align="right" id="test" value="0,00" onkeyup="mask( this );"/>
	</body>
</html>

edit: refatoradinha basica :smiley:

plentz

Vou precisar de um desses pro Padawan’s validador :smiley:

D

HUHUHUHUH

VALEUZ!

_fs

hehehehe ;D

Vê se estas te ajudam Diego.

A primeira é para formatar campos que já tem algum valor, e a outra é para mascarar enquanto digita.
Se chingar nas linhas de String[ index ], substitui por String.charAt( index ).
A formatação para money é so um teste, não funciona de maneira correta. E o mesmo problema com eventos citado acima ocorre:

var slash = "#";
function format( pattern, el )
{
	var val = el.value;
	var formatted = '';
	
	var v = 0;
	for( var i = 0; i < pattern.length; i++ )
		formatted += ( pattern[ i ] == slash ) ? ( val[ v++ ] || '' ) : pattern[ i ];
	
	el.value = formatted;
}

function mask( pattern, el, event )
{
	var val = el.value;
	var len = val.length;

	el.setAttribute( 'maxlength', pattern.length );
	
	if( pattern[ len ].indexOf( slash ) < 0 )
		el.value += pattern[ len ];
}


<html>
	<head>
		<title>Mask Testing</title>
		
		<style>
			body, p, input
			{
				font-family: verdana;
				font-size: 12px;
			}
		</style>
		
		<script language="javascript" src="FormatUtils.js"></script>
	</head>
	
	<body>
		<p>
			<h1>Format Testing</h1>
					
			Test Value: <input type="text" id="test" value="123456"/>
			Pattern: <select onchange="document.getElementById( 'pattern' ).value = this.value">
						<option value="R$ ##.###,##">R$ ##.###,##</option>
						<option value="###.###.###-##">###.###.###-##</option>
						<option value="#.##.###">#.##.###</option>
						<option value="##/##/####">##/##/####</option>
						<option value="###.###"/>###.###</option>
						<option value="#.##.##.#"/>#.##.##.#</option>	
					</select>
			<input type="text" id="pattern" value="R$ ##.###,##"/>
			<input type="button" value="Format" id="format"
				onclick="format( document.getElementById( 'pattern' ).value, document.getElementById( 'test' ) );" />
		</p>
		<hr/>
		<p>
			<h1>Mask Testing</h1>
					
			Test Value: <input type="text" id="test2" value=""
							onkeyup="mask( document.getElementById( 'pattern2' ).value, this, event );"/>
			Pattern: <select onchange="document.getElementById( 'pattern2' ).value = this.value">
						<option value="###.###.###-##">###.###.###-##</option>
						<option value="##/##/####">##/##/####</option>
						<option value="#.##.###">#.##.###</option>
						<option value="###.###"/>###.###</option>
						<option value="#.##.##.#"/>#.##.##.#</option>	
					</select>
			<input type="text" id="pattern2" value="###.###.###-##"/>
		</p>
	</body>
</html>
oliveirarenan

Lipe,

Aproveitando a deixa, eu precisaria fazer uma máscara em JS.

Tipo, quando o usuario digitar apenas 1(UM) número em um campo onde o limite é 3, ao mudar o foco, eu precisaria substituir por ZERO para completar 3 numbers, entende?

tipo, eu insiro o numero 1
ao mudar o foco ele fica assim: 001

se eu preencher 23
ao mudar o foco ele fica assim: 023

se puder, me ajude!!!

valeuz

:wink:

fenrir

Trofeu ACME pra voce :lol: - mexer sempre (e de forma correta) eh justamente o que faz a qualidade de um software aumentar. Conheca mais sobre Refactoring ;)

Concordo…CONTANTO que você tenha tempo para fazer isso e tempo para corrigir os bugs que possam vir em decorrência dessa alteração!!!

P.S.: onde eu pego o troféu?!? :stuck_out_tongue:

Criado 21 de setembro de 2004
Ultima resposta 22 de set. de 2004
Respostas 10
Participantes 7