How to calculate 2 inputs with comma and appear in a third input?

Asked

Viewed 85 times

-5

I have this script but it doesn’t work:

<input type="radio"  autocomplete="off" required value="Dinheiro e Cartão" name="pagamento" id="termos2"/> <span class="titulos_pgmnts">Dinheiro e Cartão</span><br>
                <div id="termoTexto2">
                <input type="text" id="soma1" value="<?php echo number_format($vtotal,2,",","."); // retorna: 270.78 ?>" name="">
                    <p></p>
                        <span class="titulos_pgmnts">Quanto em Dinheiro:</span> <input id="soma2" type="text" onKeyUp="mascaraMoeda(this, event)" autocomplete="off" autocomplete="off" value="" class="qtds_burgers" name="valortroco" placeholder="Digite o Valor" maxlength="6" onKeyPress="return(moeda(this,'.',',',event))"><p></p>
                    <p></p>
                        <span class="titulos_pgmnts">Restante no Cartão:</span> <input readonly id="result" type="text"  autocomplete="off" autocomplete="off"  class="qtds_burgers" name="valortroco" placeholder="0,00" maxlength="6" onKeyPress="return(moeda(this,'.',',',event))"><p></p>
                    <p></p>
                </div>
                <p></p>
    <script>
    //restantes entre cartão e dinheiro
    jQuery(document).ready(function(){
  jQuery('input').on('keyup',function(){
    if(jQuery(this).attr('name') === 'result'){
    return false;
    }
  
    var soma1 = (jQuery('#soma1').val() == '' ? 0 : jQuery('#soma1').val());
    var soma2 = (jQuery('#soma2').val() == '' ? 0 : jQuery('#soma2').val());
    var result = (parseInt(soma1) - parseInt(soma2));
    jQuery('#result').val(result);
  });
});
    </script>
  • your question is not clear, put the full html and show what you want to do

  • Ricardo edited there

  • It is returning me whole numbers I wanted to calculate with commas ex.: 22.50 - 20.00 = 2.50

2 answers

0

To be able to do this calculation it is necessary first to replace point to comma. In order for the number to be in a standard format the IEEE 754 which is the international standard for floating point binary number representation.

For this we must replace comma occurrences (,) to point (.):

const soma1f = parseFloat(soma1.replace(/\s/g, "").replace(",", "."));
const soma2f = parseFloat(soma2.replace(/\s/g, "").replace(",", "."));
const result = soma1f - soma2f;
console.log(result);

Note that there is no guarantee that there will be only one comma, since the input is of the type text. For more information on how the method works replace follows the MDN documentation about string replace.

  • \s will replace whitespace with empty string ""
  • \g is saying that we should replace all occurrences in a global way.
  • with the result of this transformation we replace vírgula (,) for ponto (.)

Then it is necessary to deal with these cases in order to avoid an exception being made when parseFloat.

After calculating the result you should show the data again using the representation with vírgula again.

const resultstr = result.toString();
const resultstrcomvirgula = resultstr.replace(".",",")

To put the values back in their variable we should just replace the variable result for resultstrcomvirgula.

jQuery('#result').val(resultstrcomvirgula);
  • Well explained however how do I implement this code I posted because I don’t know javascript

  • Sorry, I don’t know about jQuery.

0


jQuery(document).ready(function(){
  jQuery('input').on('keyup',function(){
    if(jQuery(this).attr('name') === 'result'){
    return false;
    }

    /* ####### troca virgula por ponto ############# */
    $('input[type="text"]').each(function(){
        var val = $(this).val().replace(',','.');
        $(this).val(val);
    });
    /* ############################################# */
    
    var soma1 = (jQuery('#soma1').val() == '' ? 0 : jQuery('#soma1').val());
    var soma2 = (jQuery('#soma2').val() == '' ? 0 : jQuery('#soma2').val());

    // use prseFloat 
    var result = (parseFloat(soma1) - parseFloat(soma2));

/* ########################## Solução com toLocaleString() ################# */  
//com R$
result = result.toLocaleString('pt-br',{style: 'currency', currency: 'BRL'});

//sem R$
//result = result.toLocaleString('pt-br', {minimumFractionDigits: 2}); 
   /* ######################################################################### */ 
    
    jQuery('#result').val(result );
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio"  autocomplete="off" required value="Dinheiro e Cartão" name="pagamento" id="termos2"/> <span class="titulos_pgmnts">Dinheiro e Cartão</span><br>
      <div id="termoTexto2">
          <input type="text" id="soma1" value="270.78" name="">
          <p></p>
          <span class="titulos_pgmnts">Quanto em Dinheiro:</span> <input id="soma2" type="text" autocomplete="off" autocomplete="off" value="" class="qtds_burgers" name="valortroco" placeholder="Digite o Valor" maxlength="6"><p></p>
          <p></p>
          <span class="titulos_pgmnts">Restante no Cartão:</span> <input readonly id="result" type="text"  autocomplete="off" autocomplete="off"  class="qtds_burgers" name="valortroco" placeholder="0,00" maxlength="6" onKeyPress="return(moeda(this,'.',',',event))"><p></p>
          <p></p>
          <p></p>
     </div>
     <p></p>

  • Only one doubt has to put when typing in How much money he appear with , is appearing with .

  • @Felipe, it is possible yes but will give zebra in the Remaining input in the Card since the function fires in the keyup and there will only work if you type with dot

  • No problem @Leo Thanks so much for your attention!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.