Auto Calculating Form Feilds

Hi all!
I have a form as below:

<script type="text/javascript">
function addRow(tableID) 
{
    		var table = document.getElementById(tableID);
    		var rowCount = table.rows.length;
			if(rowCount<3)
				{
    			var row = table.insertRow(rowCount);
    			var colCount = table.rows[0].cells.length;
    			for(var i=0; i<colCount; i++)
				 		 {
        				var newcell = row.insertCell(i);
        				newcell.innerHTML = table.rows[0].cells[i].innerHTML;
        				//alert(newcell.childNodes);
        			        switch(newcell.childNodes[0].type) 
							{
            				case "text":
                				newcell.childNodes[0].value = "";
                			break;
            				case "checkbox":
                				newcell.childNodes[0].checked = false;
                			break;
            				case "select-one":
                				newcell.childNodes[0].selectedIndex = 0;
                			break;
        					}
    					}
				}

		else 
		{
		alert("Maximum Limit Of 3 Rows Reached");
		}
}
function deleteRow(tableID)
{
    		try
				 {
        		var table = document.getElementById(tableID);
        		var rowCount = table.rows.length;

        			for(var i=0; i<rowCount; i++) 
						{
            			var row = table.rows[i];
            			var chkbox = row.cells[0].childNodes[0];
            
            			if (null != chkbox && true == chkbox.checked) 
							{
                			if (rowCount <= 1) 
								{
                    			alert("Cannot delete all the rows.");
                    			break;
                				}
                
                			table.deleteRow(i);
                			rowCount--;
                			i--;
            				}

        				}
    				} catch(e) 
						{
        				alert(e);
    					}
}
</script>
<form name="newquotation1" method="post" action="invoice_data.php" onSubmit="return validateForm(this)">
<table align="center">
<tr>
<td align="center" colspan="2"><span class="style2">All Fields Are Mandatory.</span></td>
</tr>
<tr>
<?
$query=mysql_query
("SELECT * FROM existing_clients_invoice");
if(mysql_num_rows($query) > 0)
{
while($row=mysql_fetch_array($query))
{
if($row!=0)
{
$id=$row['inv_id']+1;
}
}
}
else
{
$id=1;
}
$ini="IN";
$year=date("y");
$invoice= strtoupper($ini) . '-'  .($year) . '-' . '00' .$id;
?>
<td>Invoice Number:</td>
<td><input type="text" name="number" readonly"" value="<?PHP echo $invoice; ?>"></td>
</tr>
<tr>
<td>Client Name:</td>
<td>
<?PHP
$query=mysql_query("SELECT * FROM client_master");
echo "<select name='name'>";
while($row=mysql_fetch_array($query))
{
echo "<option value=$row[client_id]>
$row[client_name]</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr>
<td>Work Order Number:</td>
<td width="300">Applicable&nbsp;<input name="radio" type="radio" value="applicable">&nbsp;
<?PHP
$query=mysql_query("SELECT * FROM existing_clients");
echo "<select name='work'>";
while($row=mysql_fetch_array($query))
{
echo "<option value=$row[exi_work_number]>
$row[exi_work_number]</option>";
}
echo "</select>";
?>
&nbsp;Not Applicable&nbsp;<input name="radio" type="radio" value="notapplicable" >
</td>
</tr>
<tr>
<td>Invoice Date:</td>
<td><input id="demo3" name="date" type="text" >
<a href="javascript:NewCssCal('demo3','yyyymmdd')">
<img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
</tr>
<tr>
<td>Sales Person:</td>
<td><input type="text" name="sales_person"></td>
</tr>
<tr>
<td>Job:</td>
<td><input type="text" name="job"></td>
</tr>
<tr>
<td>Payment Terms:</td>
<td><input type="text" name="terms"></td>
</tr>
<tr>
<td>Due Date:</td>
<td><input id="demo4" name="due_date" type="text" >
<a href="javascript:NewCssCal('demo4','yyyymmdd')">
<img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>
</tr>
</table>
<tr>
<td><input type="button" value="Add Row" onClick="addRow('dataTable')" ></td>
<table align="center" id="dataTable" width="1000">
<tr>
<td>Qty:</td>
<td><input type="text" name="qty[]"></td>
<td>Description:</td>
<td><input type="text" name="description[]" ></td>
<td>Unit Price:</td>
<td><input type="text" name="unit_price[]" ></td>
<td>Line Total:</td>
<td><input type="text" name="line_total[]" ></td>
</tr>
</table>
<table align="center" width="1000">
<tr>
<td>Subtotal:</td>
<td><input type="text" name="subtotal"></td>
<td>Taxes:</td>
<td><input type="text" name="tax"></td>
<td>Advance:</td>
<td><input type="text" name="advance"></td>
<td>Total:</td>
<td><input type="text" name="total"></td>
</tr>
</table>
<table align="center">
<tr>
<td><input name="submit" type="submit" value="Submit"></td>
</tr>
</table>
</form>

Problem is, I want to display values in the text fields as below:

line_total=qty*unit_price;
subtotal=line_total[];
total=subtotal+tax-advance;

Can anyone help me out?I donno a bit of javascript!!:cool:

You need to give your form and each of your input fields a unique ID, then after you have output the form you can call a javascript function to fill those fields in for you.

The JS function will need to be passed the values you want displayed, so if you more proficient in PHP than JS I suggest you do all the calculations in PHP then pass those final values to the JS function.

The javascript function can access and change the fields in your form using the
this.document.formname.fieldname.value
operator.

Can you give me some example please?

 
<script type="text/javascript"> 
    // Pre populated array of data 
    var myData = new Array(); 
    myData[1] = 'Some text'; 
    myData[2] = 'Some other text'; 
</script>
 
<form id="example" name="example"> 
        <select id="selector" name="selector"> 
                <option value="" selected></option> 
                <option value=1>One</option> 
                <option value=2>Two</option> 
        </select> 
        <br /> 
        <input type="text" value="" id="populateme" name="populateme" /> 
</form> 
 
<script type="text/javascript"> 
        document.example.selector.onchange = updateText; 
 
        function updateText() { 
          var obj_sel = document.example.selector; 
          document.example.populateme.value = myData[obj_sel.value]; 
    } 
</script>

:slight_smile:

Thx Mandes.I will try this on and get back to you!! :slight_smile:

Hi all!
I have a form as below:

<script type="text/javascript">

function addRow(tableID) 

{

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;

            if(rowCount<3)

                {

                var row = table.insertRow(rowCount);

                var colCount = table.rows[0].cells.length;

                for(var i=0; i<colCount; i++)

                          {

                        var newcell = row.insertCell(i);

                        newcell.innerHTML = table.rows[0].cells[i].innerHTML;

                        //alert(newcell.childNodes);

                            switch(newcell.childNodes[0].type) 

                            {

                            case "text":

                                newcell.childNodes[0].value = "";

                            break;

                            case "checkbox":

                                newcell.childNodes[0].checked = false;

                            break;

                            case "select-one":

                                newcell.childNodes[0].selectedIndex = 0;

                            break;

                            }

                        }

                }



        else 

        {

        alert("Maximum Limit Of 3 Rows Reached");

        }

}

function deleteRow(tableID)

{

            try

                 {

                var table = document.getElementById(tableID);

                var rowCount = table.rows.length;



                    for(var i=0; i<rowCount; i++) 

                        {

                        var row = table.rows[i];

                        var chkbox = row.cells[0].childNodes[0];

            

                        if (null != chkbox && true == chkbox.checked) 

                            {

                            if (rowCount <= 1) 

                                {

                                alert("Cannot delete all the rows.");

                                break;

                                }

                

                            table.deleteRow(i);

                            rowCount--;

                            i--;

                            }



                        }

                    } catch(e) 

                        {

                        alert(e);

                        }

}

</script>

<form name="newquotation1" method="post" action="invoice_data.php" onSubmit="return validateForm(this)">

<table align="center">

<tr>

<td align="center" colspan="2"><span class="style2">All Fields Are Mandatory.</span></td>

</tr>

<tr>

<?

$query=mysql_query

("SELECT * FROM existing_clients_invoice");

if(mysql_num_rows($query) > 0)

{

while($row=mysql_fetch_array($query))

{

if($row!=0)

{

$id=$row['inv_id']+1;

}

}

}

else

{

$id=1;

}

$ini="IN";

$year=date("y");

$invoice= strtoupper($ini) . '-'  .($year) . '-' . '00' .$id;

?>

<td>Invoice Number:</td>

<td><input type="text" name="number" readonly"" value="<?PHP echo $invoice; ?>"></td>

</tr>

<tr>

<td>Client Name:</td>

<td>

<?PHP

$query=mysql_query("SELECT * FROM client_master");

echo "<select name='name'>";

while($row=mysql_fetch_array($query))

{

echo "<option value=$row[client_id]>

$row[client_name]</option>";

}

echo "</select>";

?>

</td>

</tr>

<tr>

<td>Work Order Number:</td>

<td width="300">Applicable&nbsp;<input name="radio" type="radio" value="applicable">&nbsp;

<?PHP

$query=mysql_query("SELECT * FROM existing_clients");

echo "<select name='work'>";

while($row=mysql_fetch_array($query))

{

echo "<option value=$row[exi_work_number]>

$row[exi_work_number]</option>";

}

echo "</select>";

?>

&nbsp;Not Applicable&nbsp;<input name="radio" type="radio" value="notapplicable" >

</td>

</tr>

<tr>

<td>Invoice Date:</td>

<td><input id="demo3" name="date" type="text" >

<a href="javascript:NewCssCal('demo3','yyyymmdd')">

<img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>

</tr>

<tr>

<td>Sales Person:</td>

<td><input type="text" name="sales_person"></td>

</tr>

<tr>

<td>Job:</td>

<td><input type="text" name="job"></td>

</tr>

<tr>

<td>Payment Terms:</td>

<td><input type="text" name="terms"></td>

</tr>

<tr>

<td>Due Date:</td>

<td><input id="demo4" name="due_date" type="text" >

<a href="javascript:NewCssCal('demo4','yyyymmdd')">

<img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td>

</tr>

</table>

<tr>

<td><input type="button" value="Add Row" onClick="addRow('dataTable')" ></td>

<table align="center" id="dataTable" width="1000">

<tr>

<td>Qty:</td>

<td><input type="text" name="qty[]"></td>

<td>Description:</td>

<td><input type="text" name="description[]" ></td>

<td>Unit Price:</td>

<td><input type="text" name="unit_price[]" ></td>

<td>Line Total:</td>

<td><input type="text" name="line_total[]" ></td>

</tr>

</table>

<table align="center" width="1000">

<tr>

<td>Subtotal:</td>

<td><input type="text" name="subtotal"></td>

<td>Taxes:</td>

<td><input type="text" name="tax"></td>

<td>Advance:</td>

<td><input type="text" name="advance"></td>

<td>Total:</td>

<td><input type="text" name="total"></td>

</tr>

</table>

<table align="center">

<tr>

<td><input name="submit" type="submit" value="Submit"></td>

</tr>

</table>

</form>

Problem is, I want to display values in the text fields as below:

line_total=qty*unit_price;

subtotal=line_total[];

total=subtotal+tax-advance; 

Can anyone help me out?I donno a bit of javascript!!

The best way to do it is to select the product first, have the program fill the unit price box from an array that connects product name with unit price and then enter the quantity. The line total can then be calculated automatically as soon as the quantity is entered.

You then need to loop through all the lines adding up the totals. The looping is necessary, as the user may go back and change one of the already entered quantities or products, which will change all of your totals.

Thx AllanP.
I am trying something like this for line total:

<script type=“text/javascript”>
function line(elem) {
var a=document.getElementById(“qty”);
var b=document.getElementById(“unit_price”);
var c=a*b;
alert (c);
document.getElementById(“line_total”).onblur = c;
}
</script>

And calling it like this:

<input type=“text” name=“line_total” id=“line_total” onBlur=“return line(this)”>

But its not working may be because these values are in array.
It alerts “NaN” and dosent show any value on onblur event.

Thx Mandes.
I am trying something like this for line total:

<script type=“text/javascript”>
function line(elem) {
var a=document.getElementById(“qty”);
var b=document.getElementById(“unit_price”);
var c=a*b;
alert (c);
document.getElementById(“line_total”).onblur = c;
}
</script>

And calling it like this:

<input type=“text” name=“line_total” id=“line_total” onBlur=“return line(this)”>

But its not working may be because these values are in array.
It alerts “NaN” and dosent show any value on onblur event.

var a=document.getElementById(“qty”).value;
var b=document.getElementById(“unit_price”).value;

???

Wow thats working just fine! But still not showing value in line_total field :frowning:

Hi. Is alert(c) showing the correct value? Do you want the value, in the textbox, to change on the entry of the final number, unit_price, or when the user clicks a button to sum the 2 numbers ? Because their are two ways of doing this, and that would help me alot with the final code and your requirements.

Thanks.

 
document.getElementById("line_total").value = c;


Yeah, I was going to suggest that, but I didn’t know if he/she wanted the value to be calculated “onblur” or clicking a mouse. Because if it was a button click, which would be prefered, I could have wrote a piece of modular code for the solution. I never really like “onblur” or “onfocus” unless it is a JS game…

I just assumed that if the qty and untiprice were changing the total line price should change too :wink:

No doubt we’ll be told in due course :smiley:

Sry for late reply guys!!
I dont know how can I do this, but javascript is pretty easier I guess.
So I just wanted to show qty*unit_price in line_total and then insert the value into database also.I was alerting the values just to know if thing is going well.
Yeh its showing the value in alert box, but not in the feild.

Yuhu!!!
Its working like miracle :):):slight_smile:
Thanks for your concern and time Mandes and USPatriot!!
Now real problem is the feilds are dynamic and I want to add more than 1 line_total feilds and show its value in sub_total.
Dont know how can I do this with js.

Have you added the id to each of these fields? Your original html had only names.

Also, it should really be
<script type=“text/javascript”>
<!–
function line() {
var a=parseFloat(document.getElementById(“qty”).value);
var b=parseFloat(document.getElementById(“unit_price”).value);
var c=a*b;
alert (c);
document.getElementById(“line_total”).value = c;
}
//–>
</script>

You need to convert the strings in each box to a number before any Math operation.

I don’t think you should expect the user to know the correct format for the product description, or the unit price. These need to be available to them as part of your program.

Yeh so far my code is:

<script type=“text/javascript”>

function addRow(tableID)

{

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;

        if(rowCount&lt;3)

            {

            var row = table.insertRow(rowCount);

            var colCount = table.rows[0].cells.length;

            for(var i=0; i&lt;colCount; i++)

                      {

                    var newcell = row.insertCell(i);

                    newcell.innerHTML = table.rows[0].cells[i].innerHTML;

                    //alert(newcell.childNodes);

                        switch(newcell.childNodes[0].type) 

                        {

                        case "text":

                            newcell.childNodes[0].value = "";

                        break;

                        case "checkbox":

                            newcell.childNodes[0].checked = false;

                        break;

                        case "select-one":

                            newcell.childNodes[0].selectedIndex = 0;

                        break;

                        }

                    }

            }



    else 

    {

    alert("Maximum Limit Of 3 Rows Reached");

    }

}

function deleteRow(tableID)

{

        try

             {

            var table = document.getElementById(tableID);

            var rowCount = table.rows.length;



                for(var i=0; i&lt;rowCount; i++) 

                    {

                    var row = table.rows[i];

                    var chkbox = row.cells[0].childNodes[0];

        

                    if (null != chkbox && true == chkbox.checked) 

                        {

                        if (rowCount &lt;= 1) 

                            {

                            alert("Cannot delete all the rows.");

                            break;

                            }

            

                        table.deleteRow(i);

                        rowCount--;

                        i--;

                        }



                    }

                } catch(e) 

                    {

                    alert(e);

                    }

}

</script>

<form name=“newquotation1” method=“post” action=“invoice_data.php” onSubmit=“return validateForm(this)”>

<tr>

<td><input type=“button” value=“Add Row” onClick=“addRow(‘dataTable’)” ></td>

<table align=“center” id=“dataTable” width=“912”>

<tr>

<td width=“68”>Quantity: </td>

<td width=“144”><input type=“text” name=“qty” id=“qty”></td>

<td width=“77”>Description: </td>

<td width=“144”><input type=“text” name=“description” id=“description”></td>

<td width=“80”>Unit Price: </td>

<td width=“144”><input type=“text” name=“unit_price” id=“unit_price”></td>

<td width=“75”>Line Total: </td>

<td width=“144”><input type=“text” name=“line_total” id=“line_total” onBlur=“return line(this)” readonly""></td>

</tr>

</table>

<table align=“center” width=“913”>

<tr>

<td width=“67”>Subtotal: </td>

<td width=“146”><input type=“text” name=“subtotal” id=“subtotal” readonly""></td>

<td width=“75”>Taxes: </td>

<td width=“144”><input type=“text” name=“tax” id=“tax”></td>

<td width=“81”>Advance: </td>

<td width=“144”><input type=“text” name=“advance” id=“advance”></td>

<td width=“76”>Total: </td>

<td width=“144”><input type=“text” name=“total” id=“total” onBlur=“return tot(this)” readonly""></td>

</tr>

</table>

<table align=“center”>

<tr>

<td><input name=“submit” type=“submit” value=“Submit”></td>

</tr>

</table>

</form>

I came up with the function as follows.It works very well on the first row, but not on the other dynamically added rows.
Similarly, I dont know how I can calculate the sub_total value by adding line_total feilds altogether.

<script type=“text/javascript”>

function line(elem) {

var a=document.getElementById(“qty”).value;

var qt=Number(a);

var b=document.getElementById(“unit_price”).value;

var up=Number(b);

var c=qt*up;

document.getElementById(“line_total”).value = c;

}

function tot(elem) {

var d=document.getElementById(“subtotal”).value;

var st=Number(d);

var e=document.getElementById(“tax”).value;

var tx=Number(e);

var f=document.getElementById(“advance”).value;

var ad=Number(f);

var g=(st+tx)-ad;

document.getElementById(“total”).value = g;

}

</script>

Finally I got solution for this problem after a long search over internet and forum :slight_smile:
And I am thankful to all you guys for ur constant support.