Ir para conteúdo

Arquivado

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

Claudia França

Mostrar campo moeda

Recommended Posts

Como eu faço para o valor recebido em dólar ou real, mostrar os campos de moeda.

 

 <select >
            
            <option value="Real" id="valor" size="8" maxLength="8" >Real R$=</option>
            
            <option value="Dolar" id="valor" size="8" maxLength="8" >Dolar $=</option>
           
        </select>
        
        <input type "text" id="valor"  onBlur= 'pegavalor(this.value);'> </br>

 

 

Tentei algumas coisas mas, não funciona.

O resultado tem que aparecer como na imagem.

 

Captura de Tela 2018-09-26 às 16.03.58.png

Compartilhar este post


Link para o post
Compartilhar em outros sites

Claudia, saudações.

 

Tenta assim:

 

script

<script language="JavaScript" > 

    function 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 = '';
      if (len == 1) fld.value = '0'+ decSep + '0' + aux;
      if (len == 2) fld.value = '0'+ decSep + aux;
      if (len > 2) {
        aux2 = '';
        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;
        for (i = len2 - 1; i >= 0; i--)
        fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - 2, len);
      }
      return false;
    }

    function id(el) {
      return document.getElementById( el );
    }
    function total( qtde, vrUnit ) {
      return parseFloat(qtde.replace(',', '.'), 10) * parseFloat(vrUnit.replace(',', '.'), 10);
    }
    window.onload = function() {
      id('vrUnit').addEventListener('keyup', function() {
        var result = total( this.value , id('qtde').value );
        id('vrTotal').value = String(result.toFixed(2)).formatMoney();
      });

      id('qtde').addEventListener('keyup', function(){
        var result = total( id('vrUnit').value , this.value );
        id('vrTotal').value = String(result.toFixed(2)).formatMoney();
      });
    }

    String.prototype.formatMoney = function() {
      var v = this;

      if(v.indexOf('.') === -1) {
        v = v.replace(/([\d]+)/, "$1,00");
      }

      v = v.replace(/([\d]+)\.([\d]{1})$/, "$1,$20");
      v = v.replace(/([\d]+)\.([\d]{2})$/, "$1,$2");
      v = v.replace(/([\d]+)([\d]{3}),([\d]{2})$/, "$1.$2,$3");

      return v;
    };

</script>    

 

no form (INPUT), fica assim:

                    <div class="col-sm-2 invoice-col">
                      <label for="vlrUnit">Valor Unitário</label>
                      <input type="text" id='vrUnit' name="vrUnit" class="form-control" maxlength="12" 
                             onkeypress="return(currencyFormat(this,'','.',event))" >
                    </div>   

 

Espero ter ajudado.

 

Renato

Compartilhar este post


Link para o post
Compartilhar em outros sites

Claudia,

 

também pode fazer assim:

 

no form (INPUT):

            <br/>
            <label> 
              <span>Valor........:</span>
                <input type="text" name="valor" size="15" onKeyUp="dinheiro(this,15)" />
             </label>

 

script:

<script type="text/javascript">

  //Valida os campos moeda do formulário 
  function dinheiro(cur,len) {
     n='__0123456789';
     d=cur.value;
     l=d.length;
     r='';

     if (l > 0){
        z=d.substr(0,l-1);
        s='';
        a=2;

          for (i=0; i < l; i++){
              c=d.charAt(i);
              if (n.indexOf(c) > a){
                  a=1;
                  s+=c;
              };
          };


          l=s.length;
          t=len-1;
          if (l > t){
              l=t;
              s=s.substr(0,t);
          };


          if (l > 2){
              r=s.substr(0,l-2)+','+s.substr(l-2,2);
          } else {
              if (l == 2){
                  r='0,'+s;
              } else  {
                  if (l == 1){
                      r='0,0'+s;
                  };
              };
          };


          if (r=='0,00'){
             return false; 
          } else {
              l=r.length;
              if (l > 6){
                  j=l%3;
                  w=r.substr(0,j);
                  wa=r.substr(j,l-j-6);
                  wb=r.substr(l-6,6);
                  if (j > 0){
                      w+='.';
                  };

                  k=(l-j)/3-2;
                  for (i=0; i < k; i++){
                      w+=wa.substr(i*3,3)+'.';
                  };
                  r=w+wb;
              };
          };

     };

     if (r.length <= len){
      cur.value=r;
     } else {
      cur.value=z;
     };

     return 'ok';

  };

</script>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites
18 horas atrás, Paulo Cesar Di Cicco disse:

você precisa aplicar uma mascara de valor no input.
Seja em PHP ou Jquery.

Procure por number_format ou mascara de valor 

 Obrigada.

Compartilhar este post


Link para o post
Compartilhar em outros sites
Em 27/09/2018 at 10:54, Remazela disse:

Claudia,

 

também pode fazer assim:

 

no form (INPUT):


            <br/>
            <label> 
              <span>Valor........:</span>
                <input type="text" name="valor" size="15" onKeyUp="dinheiro(this,15)" />
             </label>

 

script:


<script type="text/javascript">

  //Valida os campos moeda do formulário 
  function dinheiro(cur,len) {
     n='__0123456789';
     d=cur.value;
     l=d.length;
     r='';

     if (l > 0){
        z=d.substr(0,l-1);
        s='';
        a=2;

          for (i=0; i < l; i++){
              c=d.charAt(i);
              if (n.indexOf(c) > a){
                  a=1;
                  s+=c;
              };
          };


          l=s.length;
          t=len-1;
          if (l > t){
              l=t;
              s=s.substr(0,t);
          };


          if (l > 2){
              r=s.substr(0,l-2)+','+s.substr(l-2,2);
          } else {
              if (l == 2){
                  r='0,'+s;
              } else  {
                  if (l == 1){
                      r='0,0'+s;
                  };
              };
          };


          if (r=='0,00'){
             return false; 
          } else {
              l=r.length;
              if (l > 6){
                  j=l%3;
                  w=r.substr(0,j);
                  wa=r.substr(j,l-j-6);
                  wb=r.substr(l-6,6);
                  if (j > 0){
                      w+='.';
                  };

                  k=(l-j)/3-2;
                  for (i=0; i < k; i++){
                      w+=wa.substr(i*3,3)+'.';
                  };
                  r=w+wb;
              };
          };

     };

     if (r.length <= len){
      cur.value=r;
     } else {
      cur.value=z;
     };

     return 'ok';

  };

</script>

 

Remazela, obrigada pela ajuda, refiz os testes com meu código e seguindo seu raciocínio e deu tudo certo.  Muita sabedoria para vida toda.

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ILR master
      Pessoal, pergunta bem simples. Abaixo tenho o seguinte código:
       
      <script>
      function alerta()
      {
        if (window.confirm("Você realmente quer sair?")) {
          window.open("sair.html");
      }
      }
      </script>
       
      Funciona perfeitamente, só que está abrindo em outra janela e quero que abra na mesma janela.
       
      Alguém pode me ajudar?
    • Por Giovanird
      Olá a todos!
      Tenho uma pagina que possui uma DIV onde coloquei uma pagina PHP.
      Uso a função setInterval para atualizar a pagina inclusa dentro da DIV.
      O problema é que ao acessar o site , a DIV só me mostra a pagina inclusa somente quando completo o primeiro minuto.
      Preciso que a pagina inclusa já inicie carregada
       
      Meu código JavaScript e a DIV com a pagina PHP
       
      <script> function atualiza(){ var url = 'direita.php'; $.get(url, function(dataReturn) { $('#direita').html(dataReturn); }); } setInterval("atualiza()",60000); </script> <div> <span id="direita"></span> </div>  
    • Por Thiago Duarte
      Oi, gostaria de arrastar imagem e ao soltar formar bloco html, meu bloco de html ficaria com nome, content-1.html, content-2.html, etc
       
      Alguem pode me ajudar?
    • Por belann
      Olá!
       
      Estou fazendo o upload de arquivos com fetch dessa forma
      fetch(url, {
              method: 'POST',
              headers: {'Content-Type': 'multipart/form-data',},
              body: formData 
          }).catch((error) => (console.log("Problemas com o Upload"), error));
       
      estou usando input type=file
      e criando uma const formData = new FormData(); 
      mas não faz e não dá nenhum erro.
      estou fazendo o upload com a url="http://localhost/dashboard/dados".
×

Informação importante

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