Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

rafa-martin

Como faço para formatar um campo moeda

Recommended Posts

Pessoal, preciso de um help.Eu tenho um campo que é valor moeda. E estou usando o FormatNumber. Mais não está dando certo.Como faço para que no momento em que o usuário for digitando o valor no campo ele vai já formatando?Valeu.

Compartilhar este post


Link para o post
Compartilhar em outros sites

usando formatação em javascript...

 

Tem varios exemplos no forum, mas se você não encontrar nenhum que se adeque a sua necessidadecontinua este topico lá...

 

Movendo...

 

ASP >>> Dinâmico: CSS/JavaScript/DHTML

 

Topico Movido

Compartilhar este post


Link para o post
Compartilhar em outros sites

Me matei fazendo essa porquera, mas aí vai:

 

<html><head><title>[- Validações de Formulário -]</title><script language="JavaScript">var ns6 = document.getElementById && !document.allfunction RestringeInput(maxlength,e,placeholder){ if ( window.event && event.srcElement.value.length >= maxlength ) {  return false } else if ( e.target && e.target == eval( placeholder ) && e.target.value.length >= maxlength ) {  var PressTecla = /[a-zA-Z0-9\.\,\/]/ //detecta caracteres alfanuméricos  if ( PressTecla.test ( String.fromCharCode ( e.which ) ) ) {   e.stopPropagation()  } }}function ContaLimite( maxlength , e , placeholder ) { var theform = eval( placeholder ) var lengthleft = maxlength-theform.value.length var placeholderobj = document.all ? document.all[placeholder] : document.getElementById( placeholder ) if ( window.event || e.target&&e.target == eval( placeholder ) ){  if ( lengthleft < 0 )   theform.value = theform.value.substring( 0 , maxlength )   placeholderobj.innerHTML = lengthleft }}function MostraLimite( theform,thelimit ) { var limit_text = '<span id="'+theform.toString()+'" style="font-family:Tahoma; font-size:11px; color:#990000">'+thelimit+'</span><span style="font-family:Tahoma; font-size:11px; color:#990000"> caracteres restantes.</span>'  if ( document.all || ns6 )   document.write( limit_text )  if ( document.all ) {   eval( theform ).onkeypress = function(){ return RestringeInput( thelimit,event,theform )}   eval( theform ).onkeyup = function(){ ContaLimite( thelimit,event,theform ) }  } else if ( ns6 ) {   document.body.addEventListener( 'keypress', function( event ) { RestringeInput( thelimit , event , theform ) }, true );   document.body.addEventListener( 'keyup', function( event ) { ContaLimite( thelimit , event , theform ) }, true );  }}function FormataCampo(Campo,teclapres,mascara){ //pegando o tamanho do texto da caixa de texto com delay de -1 no event //ou seja o caractere que foi digitado não ser encontado. strtext = Campo.value tamtext = strtext.length //pegando o tamanho da máscara tammask = mascara.length //criando um array para guardar cada caractere da máscara arrmask = new Array(tammask) //jogando os caracteres para o vetor for (var i = 0; i < tammask; i++){  arrmask[i] = mascara.slice(i,i+1) } //alert (teclapres.keyCode) //começando o trabalho sujo if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){  if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){   OrganizaCasa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)  } else {   DetonaEvent(Campo,strtext)  } } else {  if ((arrmask[tamtext] == "A"))    {   charupper = event.valueOf()   //charupper = charupper.toUpperCase()   DetonaEvent(Campo,strtext)   masktext = strtext + charupper   Campo.value = masktext  } }}//Adiciona todos os caracteres que podem ser usados como máscarafunction OrganizaCasa(Campo,arrpos,teclapres_key,strtext){ if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){  separador = arrpos  masktext = strtext + separador  Campo.value = masktext }}function DetonaEvent(Campo,strtext){ event.returnValue = false if (strtext != "") {  Campo.value = strtext }}function VerificaForm(){ if (document.frmteste.elements["txt.nome"].value == ""){  window.alert("O campo Nome não pode ser vazio!");  document.frmteste.elements["txt.nome"].focus();  return false; } if (document.frmteste.elements["txt.endereco"].value == ""){  window.alert("O campo Endereço não pode ser vazio!");  document.frmteste.elements["txt.endereco"].focus();  return false; } if (document.frmteste.elements["txt.moeda"].value.length > "10") {  window.alert("O campo Moeda não pode ter mais de 10 caracteres!");  document.frmteste.elements["txt.moeda"].focus();  return false; }}function NumberOnly() { if ( event.keyCode < 48 || event.keyCode > 57 ) { //Só aceita caracteres com código ASCII entre 48..57 (números)  event.returnValue = false; }}// Esta function está configurada para o campo receber duas casas após a vírgulafunction currencyFormat(fld, milSep, decSep, e) { var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (whichCode == 13) return true;  // Enter key = String.fromCharCode(whichCode);  // Get key value from key code if (strCheck.indexOf(key) == -1) return false;  // Not a valid key len = fld.value.length; for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); aux += key; len = aux.length; if (len == 0) fld.value = ''; // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + '0' + senão, apenas + '0' + if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula) // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + senão, não coloca if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0' // Aqui tem que testar: se $Column->{decimals} for 3 coloca essa linha senão não coloca //if (len == 3) fld.value = '0' + decSep + aux + aux2; // Adicionei esta linha // Aqui tem que colocar a variável $decimal if (len > 2) { // Alterei de 2 para 3  aux2 = '';  // A cada três caracteres adiciona um milSep (ponto ".")  for (j = 0, i = len - 3; i >= 0; i--) {   if (j == 3) {    aux2 += milSep;    j = 0;   }   aux2 += aux.charAt(i);   j++;  }  fld.value = '';  len2 = aux2.length;  // Aqui tem que testar: se $Column->{decimals} for 3 coloca i > 0 senão coloca i >= 0  for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0  fld.value += aux2.charAt(i);  // Aqui tem que coloca a variável mo lugar do 3  fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula) } return false;}function Limitar (what,limit) { if (what.value.length>=limit) return false;}</script><style type="text/css">.txt{  font-family: Tahoma;  font-size: 11px;  color: #006699;  border-top: 1px inside #000000;  border-left: 1px inside #000000;  border-bottom: 1px solid #F3F3F3;  border-right: 1px solid #F3F3F3}.textarea{  font-family: Tahoma;  font-size: 11px;  color: #006699;  border-top: 1px inside #000000;  border-left: 1px inside #000000;  border-bottom: 1px solid #F0F0F0;  border-right: 1px solid #F0F0F0}.btn{  font-family: Verdana;  font-size: 11px;  font-weight: bold;  color: #006699;  border: 1px solid #006699;  background-color: #FFFFFF}table{  font-family: Verdana;  font-size: 11px;  color: #006699}body{  font-family: Verdana;  font-size: 11px;  color: #006699}</style></head><body topmargin="30" leftmargin="0" marginheight="0" marginwidth="0"><form name="frmteste" onSubmit="return VerificaForm();ValidaMoeda()" method="post"> <table border="0" cellpadding="3" cellspacing="0" align="center">  <tr>   <th colspan="2" align="left">Formulário para validação de campos.</th>  </tr>  <tr>   <td>Nome:</td>   <td><input type="text" name="txt.nome" size="30" class="txt"></td>  </tr>  <tr>   <td>Número:</td>   <td><input type="text" name="txt.numero" size="20" onkeypress="NumberOnly()" class="txt"></td>  </tr>  <tr>   <td>Endereço:</td>   <td><input type="text" name="txt.endereco" size="20" class="txt"></td>  </tr>  <tr>   <td>Data:</td>   <td><input type=text name="txt.data" size="10" onkeypress="FormataCampo(this,event,'##/##/####');NumberOnly()" maxlength="10" class="txt"></td>  </tr>  <tr>   <td>Valor (R$):</td>   <td><input type=text name="txt.valor" class="txt" onKeyPress="return(currencyFormat(this,'.',',',event));" style="text-align:right"> <small>(*Digite apenas valores monetários.)</small></td>  </tr>  <tr>   <td colspan="2">Mensagem:</td>  </tr>  <tr>   <td colspan="2">    <textarea name="txt.teste" cols="40" rows="5" class="textarea"></textarea><br>    <script>     MostraLimite(document.frmteste.elements["txt.teste"],100) //frmteste = nome do form , txt.teste = nome da textarea e 100 = quantidade de caracteres permitidos.    </script>   </td>  </tr>  <tr>   <td align="center"><input type="submit" name="btn" value="Enviar" class="btn"></td>   <td align="left"><input type="reset" name="btn_limpar" value="Limpar" class="btn"></td>  </tr> </table></form></body></html>

http://forum.imasters.com.br/public/style_emoticons/default/clap.gif

Compartilhar este post


Link para o post
Compartilhar em outros sites

Me matei fazendo essa porquera, mas aí vai:

<html><head><title>[- Validações de Formulário -]</title><script language="JavaScript">var ns6 = document.getElementById && !document.allfunction RestringeInput(maxlength,e,placeholder){ if ( window.event && event.srcElement.value.length >= maxlength ) {  return false } else if ( e.target && e.target == eval( placeholder ) && e.target.value.length >= maxlength ) {  var PressTecla = /[a-zA-Z0-9\.\,\/]/ //detecta caracteres alfanuméricos  if ( PressTecla.test ( String.fromCharCode ( e.which ) ) ) {   e.stopPropagation()  } }}function ContaLimite( maxlength , e , placeholder ) { var theform = eval( placeholder ) var lengthleft = maxlength-theform.value.length var placeholderobj = document.all ? document.all[placeholder] : document.getElementById( placeholder ) if ( window.event || e.target&&e.target == eval( placeholder ) ){  if ( lengthleft < 0 )   theform.value = theform.value.substring( 0 , maxlength )   placeholderobj.innerHTML = lengthleft }}function MostraLimite( theform,thelimit ) { var limit_text = '<span id="'+theform.toString()+'" style="font-family:Tahoma; font-size:11px; color:#990000">'+thelimit+'</span><span style="font-family:Tahoma; font-size:11px; color:#990000"> caracteres restantes.</span>'  if ( document.all || ns6 )   document.write( limit_text )  if ( document.all ) {   eval( theform ).onkeypress = function(){ return RestringeInput( thelimit,event,theform )}   eval( theform ).onkeyup = function(){ ContaLimite( thelimit,event,theform ) }  } else if ( ns6 ) {   document.body.addEventListener( 'keypress', function( event ) { RestringeInput( thelimit , event , theform ) }, true );   document.body.addEventListener( 'keyup', function( event ) { ContaLimite( thelimit , event , theform ) }, true );  }}function FormataCampo(Campo,teclapres,mascara){ //pegando o tamanho do texto da caixa de texto com delay de -1 no event //ou seja o caractere que foi digitado não ser encontado. strtext = Campo.value tamtext = strtext.length //pegando o tamanho da máscara tammask = mascara.length //criando um array para guardar cada caractere da máscara arrmask = new Array(tammask) //jogando os caracteres para o vetor for (var i = 0; i < tammask; i++){  arrmask[i] = mascara.slice(i,i+1) } //alert (teclapres.keyCode) //começando o trabalho sujo if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9"))))){  if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13)){   OrganizaCasa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)  } else {   DetonaEvent(Campo,strtext)  } } else {  if ((arrmask[tamtext] == "A"))    {   charupper = event.valueOf()   //charupper = charupper.toUpperCase()   DetonaEvent(Campo,strtext)   masktext = strtext + charupper   Campo.value = masktext  } }}//Adiciona todos os caracteres que podem ser usados como máscarafunction OrganizaCasa(Campo,arrpos,teclapres_key,strtext){ if (((arrpos == "/") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8)){  separador = arrpos  masktext = strtext + separador  Campo.value = masktext }}function DetonaEvent(Campo,strtext){ event.returnValue = false if (strtext != "") {  Campo.value = strtext }}function VerificaForm(){ if (document.frmteste.elements["txt.nome"].value == ""){  window.alert("O campo Nome não pode ser vazio!");  document.frmteste.elements["txt.nome"].focus();  return false; } if (document.frmteste.elements["txt.endereco"].value == ""){  window.alert("O campo Endereço não pode ser vazio!");  document.frmteste.elements["txt.endereco"].focus();  return false; } if (document.frmteste.elements["txt.moeda"].value.length > "10") {  window.alert("O campo Moeda não pode ter mais de 10 caracteres!");  document.frmteste.elements["txt.moeda"].focus();  return false; }}function NumberOnly() { if ( event.keyCode < 48 || event.keyCode > 57 ) { //Só aceita caracteres com código ASCII entre 48..57 (números)  event.returnValue = false; }}// Esta function está configurada para o campo receber duas casas após a vírgulafunction currencyFormat(fld, milSep, decSep, e) { var sep = 0; var key = ''; var i = j = 0; var len = len2 = 0; var strCheck = '0123456789'; var aux = aux2 = ''; var whichCode = (window.Event) ? e.which : e.keyCode; if (whichCode == 13) return true;  // Enter key = String.fromCharCode(whichCode);  // Get key value from key code if (strCheck.indexOf(key) == -1) return false;  // Not a valid key len = fld.value.length; for(i = 0; i < len; i++) if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; aux = ''; for(; i < len; i++) if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); aux += key; len = aux.length; if (len == 0) fld.value = ''; // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + '0' + senão, apenas + '0' + if (len == 1) fld.value = '0' + decSep + '0' + aux; // Alterei coloquei + '0' , decSep = , (vírgula) // Aqui tem que testar: se $Column->{decimals} for 3 coloca + '0' + senão, não coloca if (len == 2) fld.value = '0' + decSep + aux; // Alterei coloquei + '0' // Aqui tem que testar: se $Column->{decimals} for 3 coloca essa linha senão não coloca //if (len == 3) fld.value = '0' + decSep + aux + aux2; // Adicionei esta linha // Aqui tem que colocar a variável $decimal if (len > 2) { // Alterei de 2 para 3  aux2 = '';  // A cada três caracteres adiciona um milSep (ponto ".")  for (j = 0, i = len - 3; i >= 0; i--) {   if (j == 3) {    aux2 += milSep;    j = 0;   }   aux2 += aux.charAt(i);   j++;  }  fld.value = '';  len2 = aux2.length;  // Aqui tem que testar: se $Column->{decimals} for 3 coloca i > 0 senão coloca i >= 0  for (i = len2 - 1; i >= 0; i--) // Alterei de i >= 0 para i > 0  fld.value += aux2.charAt(i);  // Aqui tem que coloca a variável mo lugar do 3  fld.value += decSep + aux.substr(len - 2, len); // O número dois é o valor chave (número de casas que vem depois da vírgula) } return false;}function Limitar (what,limit) { if (what.value.length>=limit) return false;}</script><style type="text/css">.txt{  font-family: Tahoma;  font-size: 11px;  color: #006699;  border-top: 1px inside #000000;  border-left: 1px inside #000000;  border-bottom: 1px solid #F3F3F3;  border-right: 1px solid #F3F3F3}.textarea{  font-family: Tahoma;  font-size: 11px;  color: #006699;  border-top: 1px inside #000000;  border-left: 1px inside #000000;  border-bottom: 1px solid #F0F0F0;  border-right: 1px solid #F0F0F0}.btn{  font-family: Verdana;  font-size: 11px;  font-weight: bold;  color: #006699;  border: 1px solid #006699;  background-color: #FFFFFF}table{  font-family: Verdana;  font-size: 11px;  color: #006699}body{  font-family: Verdana;  font-size: 11px;  color: #006699}</style></head><body topmargin="30" leftmargin="0" marginheight="0" marginwidth="0"><form name="frmteste" onSubmit="return VerificaForm();ValidaMoeda()" method="post"> <table border="0" cellpadding="3" cellspacing="0" align="center">  <tr>   <th colspan="2" align="left">Formulário para validação de campos.</th>  </tr>  <tr>   <td>Nome:</td>   <td><input type="text" name="txt.nome" size="30" class="txt"></td>  </tr>  <tr>   <td>Número:</td>   <td><input type="text" name="txt.numero" size="20" onkeypress="NumberOnly()" class="txt"></td>  </tr>  <tr>   <td>Endereço:</td>   <td><input type="text" name="txt.endereco" size="20" class="txt"></td>  </tr>  <tr>   <td>Data:</td>   <td><input type=text name="txt.data" size="10" onkeypress="FormataCampo(this,event,'##/##/####');NumberOnly()" maxlength="10" class="txt"></td>  </tr>  <tr>   <td>Valor (R$):</td>   <td><input type=text name="txt.valor" class="txt" onKeyPress="return(currencyFormat(this,'.',',',event));" style="text-align:right"> <small>(*Digite apenas valores monetários.)</small></td>  </tr>  <tr>   <td colspan="2">Mensagem:</td>  </tr>  <tr>   <td colspan="2">    <textarea name="txt.teste" cols="40" rows="5" class="textarea"></textarea><br>    <script>     MostraLimite(document.frmteste.elements["txt.teste"],100) //frmteste = nome do form , txt.teste = nome da textarea e 100 = quantidade de caracteres permitidos.    </script>   </td>  </tr>  <tr>   <td align="center"><input type="submit" name="btn" value="Enviar" class="btn"></td>   <td align="left"><input type="reset" name="btn_limpar" value="Limpar" class="btn"></td>  </tr> </table></form></body></html>
http://forum.imasters.com.br/public/style_emoticons/default/clap.gif
Muito legal esse script.Mas eu queria saber uma coisa.Com esse aí, após digitar o valor [ no campo ta moeda ]não possível deletar os números para digitar novamente.tem como alterar?

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.