Pergunta

I have 3 text boxes whose values came from PHP and I want to add them using Javascript.

so I have this code:

function addNumbers()      
  { 
   var pa    = parseFloat(document.getElementById("pa").value) ||0;
   var ma    = parseFloat(document.getElementById("ma").value) ||0;
   var oa    = parseFloat(document.getElementById("oa").value) ||0;
   var ga    = document.getElementById("ga");      

   ga.value = (pa+ma+oa).toFixed(2);
}

and in my HTML, I have this:

<input onchange="addNumbers()" type="text" id="pa" name="pa" value="<?php echo $pas_Sum ?>" /> 
<input onchange="addNumbers()" type="text" id="ma" name="ma" value="<?php echo $mas_Sum ?>" /> 
<input onchange="addNumbers()" type="text" id="oa" name="oa" value="<?php echo $oas_Sum ?>" /> 
<input onchange="addNumbers()" type="text" id="ga" name="ga" value="" />  

The problem: The sum is not displaying in the text box "ga"

also in PHP, I have this:

$pa      = mysql_query("select SUM(PAmt) as sumPA FROM $tbl_name"); 
$pa_sum  = mysql_fetch_assoc($pa); 
$pas_Sum = number_format ($pa_sum['sumPA'], 2);

$ma      = mysql_query("select SUM(MAmt) as sumMA FROM $tbl_name"); 
$ma_sum  = mysql_fetch_assoc($ma); 
$mas_Sum = number_format ($ma_sum['sumMA'], 2);

$oa      = mysql_query("select SUM(Amt) as sumOA FROM $tbl_name"); 
$oa_sum  = mysql_fetch_assoc($oa); 
$oas_Sum = number_format ($oa_sum['sumOA'], 2);

At first I have tried to directly add the numbers using this code:

$all = $pas_Sum + $mas_Sum + $oas_Sum

and then I put this in the HTML text box

<input type="text" id="ga" name="ga" value="<?php echo $all ?>" /> 

The problem in here is that it is displaying the wrong amount. That is why I have tried using JS but I am not getting any display in the textbox. Any idea on how I should solve this issue?

Thanks

Foi útil?

Solução

If you want the values to be calculated on page load then you will need to force a change event after load has completed

DEMO http://jsfiddle.net/a3aL6/1/

(function () {
    function load2(){
        document.getElementById("ga").onchange();
    }
    if (window.addEventListener) {
        window.addEventListener('DOMContentLoaded', load2, false);
    } else {
        window.attachEvent('onload', load2);
    }
} ());

If you want the values to change as a user changes the input, without haveing to lose focu on the element, then you could consider using onkeyup instead of onchange

DEMO http://jsfiddle.net/a3aL6/2/

str_replace example

$pas_Sum =  str_replace(',', '', $pa_sum['sumPA']);
$pas_Sum = number_format (pas_Sum, 2);

Outras dicas

Try to assign value like this ,

  document.getElementsByName('ga')[0].value = ga;

where ga would be your sum ,

  ga = (pa+ma+oa).toFixed(2);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top