I can not return to the input the value of a POST in PHP

-2

I have a form with four numeric fields, ncr11 , ncr22 , ncr33 and ncr44 . There is still another field in the form, ncr , which will receive a total value, which is the sum of all four first fields. The sum I did with PHP and I was informed in another question that I should keep the action of the form blank and I run the code on the same page, however, when I refresh the page, my result field always ends up going blank.

What I would like to do is that when the user entered the values, the result field would be updated automatically.

<?php
$crTot = "";
if($_POST){
    $cr1 = $_POST['ncr11'];
    $cr2 = $_POST['ncr22'];
    $cr3 = $_POST['ncr33'];
    $cr4 = $_POST['ncr44'];
$crTot = $cr1+$cr2+$cr3+$cr4;
echo $crTot;
}
?>

<form method="post" action="">
<div id="circulantes">
    <div class="ativocirculante" id="ativocirculante">
        <h2>ATIVO CIRCULANTE<input type="text" placeholder="R$ 0,00" id="ac" readonly/></h2>
        <h4>Ativo Errático (Financeiro) <input type="text" placeholder="R$ 0,00 aplicações" id="ae"/></h4>
        <h4>Disponíveis (Caixa e Bancos)<input type="text" placeholder="R$ 0,00" id="disp"/></h4>
        <h3>ACO<input type="text" placeholder="R$ 0,00" id="aco" readonly/></h3>
        <h4>Contas a receber<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="<?php echo $crTot;?>" readonly/></h4>
        <h4 id="cr1">Até 30 dias<input type="text" placeholder="R$ 0,00" id="cr11" name="ncr11"/></h4>
        <h4 id="cr2">31 a 60 dias<input type="text" placeholder="R$ 0,00" id="cr22" name="ncr22"/></h4>
        <h4 id="cr3">61 a 90 dias<input type="text" placeholder="R$ 0,00" id="cr33" name="ncr33"/></h4>
        <h4 id="cr4">Acima de 90 dias<input type="text" placeholder="R$ 0,00" id="cr44" name="ncr44"/></h4>
        <h4>Estoque<input type="text" placeholder="R$ 0,00" id="est"/></h4>
        <h4>Adiantamento a Fornecedores<input type="text" placeholder="R$ 0,00" id="af"/></h4>
        <h4>Despesas antecipadas<input type="text" placeholder="R$ 0,00" id="da"/></h4>
</div>
    
asked by anonymous 02.10.2017 / 14:44

1 answer

1

1 - Define a fixed mask for value fields, use the jQuery Input Mask plugin, or use the input with type='number' , but this does not work in several browsers, to lock a format for number I recommend the plugin.

2 - Action blank indicates that you do not use jQuery/Ajax to submit and want it to send to the same page, then PHP that receives $_POST should be at the top of the file.

3 - As I said in '1' , to work you need a default, that is, always 'RS10,00' , or '10,00' , or '10.00' , no matter what format, what matters is what input has always the same format.

Assuming your input would have the format 'RS10.00' , use str_replace() to remove the 'R$' and number_format() to format the string to a decimal number:

<?php

$crTot = "";
if($_POST){
    $cr1 =  number_format(str_replace('R$', '', $_POST['ncr11']), 2, '.', ' ');
    $cr2 =  number_format(str_replace('R$', '', $_POST['ncr22']), 2, '.', ' ');
    $cr3 =  number_format(str_replace('R$', '', $_POST['ncr33']), 2, '.', ' ');
    $cr4 =  number_format(str_replace('R$', '', $_POST['ncr44']), 2, '.', ' ');
    $crTot = $cr1+$cr2+$cr3+$cr4;
    echo $crTot;
}
?>

And to put this value inside the input (you did right):

<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="<?php echo $crTot;?>" readonly/>

How to automatically upgrade with JS:

You first need to add some classnames identifiers to the elements below:

<input type="text" placeholder="R$ 0,00" id="cr" name="ncr" value="" class='ncrTot' readonly/>
<h4 id="cr1">Até 30 dias<input type="text" placeholder="R$ 0,00" id="cr11" name="ncr11" class='ncr11 ncr_value'/></h4>
<h4 id="cr2">31 a 60 dias<input type="text" placeholder="R$ 0,00" id="cr22" name="ncr22" class='ncr22 ncr_value' /></h4>
<h4 id="cr3">61 a 90 dias<input type="text" placeholder="R$ 0,00" id="cr33" name="ncr33" class='ncr33 ncr_value' /></h4>
<h4 id="cr4">Acima de 90 dias<input type="text" placeholder="R$ 0,00" id="cr44" name="ncr44" class='ncr44 ncr_value' /></h4>

Note that an 'ncr_value' classname has been assigned to the 4 fields in question.

Now, to put a mask that will keep a pattern to the value, let's use the jqueryinputmask plugin, just put it inside the '<head>' of your page along with jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.min.js"></script><scriptsrc="https://code.jquery.com/jquery-3.2.1.js"
              integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
              crossorigin="anonymous"></script>

Now, to apply the mask, insert the following code into your file:

$('.ncr_value').inputmask('decimal', {
                'alias': 'numeric',
                'groupSeparator': ',',
                'autoGroup': true,
                'digits': 2,
                'radixPoint': ".",
                'digitsOptional': false,
                'allowMinus': false,
                'prefix': 'R$ '
    });

If everything went right, at this point you will have input with 'R$00.00' format.

Now, to do the calculation, there are several forms, in the example, a loop will be used by the inputs, and eviting a dynamic sum:

//Indica para efetuar a soma quando for pressionado um botão com foco no input, quando o valor for alterado, ou qunado o foco seguir em diante
$(document).on('keyup blur change','.ncr_value',function(){
        var v = 0;  
        //Inicia o loop pelos cmapos
        $('.ncr_value').each(function(b,c) {   
        if ($(c).val()) {
        //Remove o 'R$' para converter em numero
        var a = $(c).val().replace('R$','');
        //Susbtitui a virgula padrão de milhares por nada para somar corretamente
        var b = a.replace(',','');
        //Usa o += para somar os valores
        v += parseFloat(b);
        }
    });
    //Preenche o elemento com classname 'ncrTot' com o resultado da soma.
    $('.ncrTot').val('R$' + v.toFixed(2));
});

I tried to explain in a simple way a way to do this, I do not know if it was so simple, to improve and much, follow an example working on fiddle:

link

    
02.10.2017 / 15:53