简体   繁体   中英

auto calculate table row having data from mysql using javascript

hi guys I have a code here that collects data from mysql and display it in html table here's the php code:

<?Php
include("database_connection.php");
$query="select money
        from `money_denomination_t`
        ";
        $select_data_Result = mysqli_query($objconn, $query);
?>

and here's HTMl code:

<table id="">
<thead>
<th>Money</th><th>x</th><th>Amount</th><th>=</th><th>Total</th>
<thead>
<?php 
$id = 0;
while($row=mysqli_fetch_array($select_data_Result))
{
    $id++;
?>
<tbody>
<tr>
<td>
<input type="text" name="money[]" value="<?php echo $row['money']; ?>" ></td>
<td>x</td>
<td><input type='text' name="amount[]"></td>
<td>=</td>
<td><input type='text' name="rowtotal[]"></td>
</tr>
</tbody>
<?php
}   
?>
<td></td><td></td><td></td><td></td><td><input type='text' name="total"></td>
</table>

What I wanted to do is to get the product of money and amount and display it in rowtotal using keyup javascript anyone who can help me achieve it

I already have here the code that sum up all the values of rowtotal and display it in textbox total and its already fine I just need help about computing each rows to integrate here:

<script>
var totalperrow = document.getElementsByName("rowtotal[]");
var totalperrow_array = Array.prototype.slice.call(totalperrow);


for(var i=0; i < totalperrow_array.length; i++){
    totalperrow_array[i].addEventListener("keyup", sum_values);
}
function sum_values(){
    var sum = 0;
    for(var i=0; i < totalperrow_array.length; i++){
        sum += parseFloat(totalperrow_array[i].value);
    }
    if(!isNaN(sum))
    {
        document.getElementsByName("total")[0].value = sum;
        alert(sum);
    }
}
</script>

Hopefully I interpreted the question correctly - the following code uses a for loop to emulate the recordset iteration and generates random amounts of money for each row. The javascript finds all the amount fields and listens for keyup events on those fields. The keyup event triggers the calculation of that row's total which also updates the grand total at the bottom of the table. Incidentally your original HTML is invalid - the last few td elements MUST be within a table row!

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>keyup sum</title>
        <style>
            body,body *{box-sizing:border-box;font-family:calibri,verdana,arial;}
            input[type='text']{padding:0.5rem;}
        </style>
    </head>
    <body>

        <table id="">
            <thead>
                <th>Money</th>
                <th>x</th>
                <th>Amount</th>
                <th>=</th>
                <th>Total</th>
            <thead>
        <?php

        $id = 0;
        for( $i=0; $i < 5; $i++ ){

            $id++;

            $row['money']=mt_rand(5,250);

        ?>
            <tbody>
                <tr>
                    <td>
                        <input type="text" name="money[]" value="<?php echo $row['money']; ?>" >
                    </td>
                    <td>x</td>
                    <td>
                        <input type='text' name="amount[]">
                    </td>
                    <td>=</td>
                    <td>
                        <input type='text' name="rowtotal[]">
                    </td>
                </tr>
        <?php
        }   
        ?>
                <tr>
                    <td colspan=4 align='right'>Grand Total</td>
                    <td><input type='text' name="total"></td>
                </tr>
            </tbody>
        </table>


        <script>

            let total=document.querySelector('input[type="text"][name="total"]');



            const calculatetotal=function(){
                let sum=0;
                Array.prototype.slice.call( document.querySelectorAll( 'input[type="text"][name="rowtotal[]"]' ) ).forEach( field=>{
                    if( !isNaN( parseFloat( field.value ) ) )sum += parseFloat( field.value );
                });
                return sum;
            }



            Array.prototype.slice.call( document.querySelectorAll( 'input[type="text"][name="amount[]"]' ) ).forEach( input=>{
                input.addEventListener('keyup', function(e){
                    if( !isNaN( this.value ) ){
                        let money = this.parentNode.parentNode.querySelector('input[type="text"][name="money[]"]')
                        let result = this.parentNode.parentNode.querySelector('input[type="text"][name="rowtotal[]"]')
                        let product = this.value * money.value;

                        result.value=product;
                        total.value=calculatetotal();
                    }
                })
            })
        </script>


    </body>
</html>

To calculate the row total the above code references the active input's parent (table) row as the base when searching for the other text fields in that row. Using querySelector you can be very specific for what you search for - a very useful reference can be found here

I guess I understood your question. I have done the same project before for a billing software. here is my js code to get the total. I hope it may help you. This is html code:

    <input  type="text" name="Total[]" onkeyup="total()"  id="Total" readonly/>
    <input type="text" name="Grandtotal[]" id="GrandTotal"/>

This is jacascript code:

 <script>
   function total() {
          var inputs = document.getElementsByName('Total'),
              result = document.getElementById('GrandTotal'),
              sum = 0;            
          for(var i=0; i<inputs.length; i++) {
              var ip = inputs[i];
              if (ip.name && ip.name.indexOf("GrandTotal") < 0) {
                  sum += parseInt(ip.value) || 0;
              }
          }
          result.value = sum;
         }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM