Jump to content

Archived

This topic is now archived and is closed to further replies.

lingo5

Please Help With Js Calculation

Recommended Posts

Hi,

I have this form:

 

<form name="form" ><td bgcolor="#F8F8F8"><input type="text" class="id" size="10" /></td>
 <td bgcolor="#F8F8F8"><input type="text" id="description[]" size="40" /></td>
 <td bgcolor="#F8F8F8"><input type="text" id="quantity[]" onchange="doMath()" size="3"/></td>
 <td bgcolor="#F8F8F8"><input type="text" id="unitprice[]" onchange="doMath()" size="10"/>
	 <td nowrap bgcolor="#F8F8F8"><input type="text" id="total[]" size="10" />
</form>

 

What i need to do is to add multiply quantity x unitprice and display the result as total.

 

This is my JS math script:

 

	 <script type="text/javascript">
function doMath()
{
// Capture the entered values of two input boxes
var quantity = document.getElementById('quantity[]').value;
var unitprice = document.getElementById('unitprice[]').value;
// Add them together and display
var sum = parseInt(quantity[]) * parseInt(unitprice[]);
document.getElementById('total[]').value = sum;
}
</script>

 

But this is not doing the calculation. Please help.

thanks

Share this post


Link to post
Share on other sites

Thanx Stephan....but i think your JS is still a bit too complicated for me at this stage.

All i need to do is multiply A*B

Share this post


Link to post
Share on other sites

Let's try to make this as simple as possible.

Demo: http://xaotique.no-ip.org/tmp/23/

 

HTML

<input type="text" style="width: 100px;" />
<input type="text" style="width: 100px;" />
<span id="result"></span>

 

For HTML, all we need is two input boxes and a spot to stick the product of the two numbers. I used CSS to limit the length of the boxes for convenience.

 

Javascript

// This will wait for the page load trigger before our JS runs.
window.addEventListener("load", function()
{
   // Select our input boxes containing the numbers to multiply.
   var input = window.document.querySelectorAll("input");

   // Function to calculate.  (I guess that's obvious) 
   function calculate()
   {
       // Since we're multiplying, a starting total of 1.  (anything multiplied by 1 is itself)
       var total = 1;

       // Loop through the inputs to deal with the values.
       for (var i in input)
       {
           // Check that the value exists.
           if (input[i].value != undefined)
           {
               // Remove anything but numbers and decimals from the input box.
               input[i].value = input[i].value.replace(/[^0-9\.]/, '');

               // Multiply the number on to our total.
               total *= Number(input[i].value);
           }
       }

       // Present the total in the area we provided.
       window.document.querySelector("#result").innerHTML = total;
   }

   // Loop through our input boxes.
   for (var i in input)
   {
       // Set default value.
       input[i].value = 0;

       // Set trigger to calculate when we press a key.
       input[i].addEventListener("keyup", calculate, false);

       // Backup trigger in case of pasting by mouse right-click.
       input[i].addEventListener("change", calculate, false);
   }
}, false);

Share this post


Link to post
Share on other sites

Thanx xaotique....the example you link to works fine, but when I try your script it doesn't work

This is what i did:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <title>Xaotique</title>
 <meta http-equiv="content-type" content="text/html;charset=utf-8" />
 <script type="text/javascript" src="js/calculator.js"></script>
</head>

<body>
 <input type="text" style="width: 100px;" />
 <input type="text" style="width: 100px;" />
 <span id="result"></span>
</body>
</html>

 

and this is my calculator.js:

 

// This will wait for the page load trigger before our JS runs.
window.addEventListener("load", function()
{
// Select our input boxes containing the numbers to multiply.
var input = window.document.querySelectorAll("input");
// Function to calculate. (I guess that's obvious) 
function calculate()
{
// Since we're multiplying, a starting total of 1. (anything multiplied by 1 is itself)
var total = 1;
// Loop through the inputs to deal with the values.
for (var i in input)
{
// Check that the value exists.
if (input[i].value != undefined)
{
// Remove anything but numbers and decimals from the input box.
input[i].value = input[i].value.replace(/[^0-9\.]/, '');
// Multiply the number on to our total.
total *= Number(input[i].value);
}
}
// Present the total in the area we provided.
window.document.querySelector("#result").innerHTML = total;
}
// Loop through our input boxes.
for (var i in input)
{
// Set default value.
input[i].value = 0;
// Set trigger to calculate when we press a key.
input[i].addEventListener("keyup", calculate, false);
// Backup trigger in case of pasting by mouse right-click.
input[i].addEventListener("change", calculate, false);
}
}, false);

Share this post


Link to post
Share on other sites

Xaotic sorry..ignore my previous post it works fine....Thanks so much!!!!!

Share this post


Link to post
Share on other sites

You weren't supposed to just copy and paste, but try and understand what was done. Since you did, the only thing I can assume is wrong is the source of the script since I don't think you changed anything else.

 

Make sure the path is correct. You could link me to where you've put it?

Also, if you're trying to run it locally, you can't do that. Well, not without having it on a webserver because running a local file in the browser won't allow JS to execute for security reasons.

Share this post


Link to post
Share on other sites

sorry Xaotic one more question,

I see your script selects all text inputs to perform the calculation. My problem is I have other text inputs in my form that are not part of the calculation.

This is my form

<form name="form" ><td bgcolor="#F8F8F8"><input type="text" class="id" size="10" /></td>

<td bgcolor="#F8F8F8"><input type="text" id="description[]" size="40" /></td>

<td bgcolor="#F8F8F8"><input type="text" id="quantity[]" onchange="doMath()" size="3"/></td>

<td bgcolor="#F8F8F8"><input type="text" id="unitprice[]" onchange="doMath()" size="10"/>

<td nowrap bgcolor="#F8F8F8"><input type="text" id="total[]" size="10" />

</form>

How can I do this?

Thanks

Share this post


Link to post
Share on other sites

Add a class to the inputs you want to calculate, then make the selector a class ".className" and cycle through them. It would work the same way.

Share this post


Link to post
Share on other sites

I'm not sure I can do that....could you please give me an example?

Thanks :confused:

Share this post


Link to post
Share on other sites

In the HTML, set the class attribute of the input tags you want to multiply.

class="myClass"

 

Then in the JS, where we selected input tags, select the class instead.

querySelectorAll(".myClass")

 

Nothing used for the tag.

Dot "." used for class names.

Pound "#" used for an ID.

 

Although, an ID can only be used once, so you would use querySelector("#id").

Share this post


Link to post
Share on other sites

Thanks that makes sense and it works perfectly as a standalone calculator.

Now....I am getting more complicated now..i need this calculator to work as part of my complete script.

Would you be so kind to try my script?

<html>
<head>
 <?php
$referencia= substr(number_format(time() * rand(),0,'',''),0,10); //random number generator
?>
<script type="text/javascript" src="../js/calculator.js"></script>
<script src="http://code.jquery.com/jquery-1.5.1.min.js"></script>
 <script>
 $(document).ready(function() {
  var id = 0; // usar esto si queremos que la i sea 1, 2, 3 etc
  var id = (<?php echo $referencia ;?>);

  // Add button functionality
  $("table.dynatable button.add").click(function() {
   id++;
   var master = $(this).parents("table.dynatable");

   // Get a new row based on the prototype row
   var prot = master.find(".prototype").clone();
   prot.attr("class", "")
   prot.find(".id").attr("value", id);

   master.find("tbody").append(prot);
  });

  // Remove button functionality
  $("table.dynatable button.remove").live("click", function() {
   $(this).parents("tr").remove();

  });
 });
 </script>

 <style>
  .dynatable {
border: solid 1px #000;
border-collapse: collapse;
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
  }
  .dynatable th,
  .dynatable td {
border: solid 1px #000;
text-align: center;
color: #FFF;
padding-top: 8px;
padding-right: 10px;
padding-bottom: 8px;
padding-left: 10px;
  }
  .dynatable .prototype {
   display:none;
  }
 .blackTXT {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
color: #333;
text-decoration: none;
}

    </style>


</head>
<body>
 <table width="901" align="center" class="dynatable">
  <thead>
   <tr>
 <th width="92" bgcolor="#787878">ID</th>
 <th width="267" bgcolor="#787878">descripción</th>
 <th width="120" bgcolor="#787878">cantidad</th>
	 <th width="136" bgcolor="#787878">precio unidad</th>
	 <th width="50" bgcolor="#787878">IVA</th>
  <th width="73" bgcolor="#787878">total</th>
  <th width="131" bgcolor="#787878"><button class="add">Add</button></th>
   </tr>
  </thead>
  <tbody>
   <tr class="prototype">
 <form name="form" ><td bgcolor="#F8F8F8">
			    <input type="ee" class="id" value="<?php echo $referencia?>" size="10" /></td>
   <td bgcolor="#F8F8F8"><input  type="text"  id="descripcion[]" size="40"  /></td>
   <td bgcolor="#F8F8F8"><input  type="text" class="number" style="width: 100px;"/></td>
   <td nowrap bgcolor="#F8F8F8"><input type="text" class="number" style="width: 100px;"/>
	 <span class="blackTXT">€</span></td>
   <td bgcolor="#F8F8F8"><span class="blackTXT">21%</span>
	 <td nowrap bgcolor="#F8F8F8"><span id="result"></span> <span class="blackTXT">€</span>
   <td bgcolor="#F8F8F8"><button class="remove">Remove</button></form>
 </tr>
 </table>
</body>
</html>

Share this post


Link to post
Share on other sites

By the way .. You should have said you were using jQuery. Your first post showed plain JS, so I stuck to that. It would have been shorter with jQuery.

Share this post


Link to post
Share on other sites

So, now we have the result id being duplicated, the classes are not all used for each calculation, and you need to apply the click trigger function to the newly created elements.

 

I would take the text fields as a whole, and apply a trigger to them that would take its parent and use the elements inside to calculate for that row.

Share this post


Link to post
Share on other sites

When we made the example, we were only using one set of numbers to calculate, so we didn't even bother putting a class to it. When you have different ones you need to do, you need to cycle through them separately to add up that row, rather than all rows combined.

 

Instead of using a bunch of different classes, use one class. One class for every text field. When it triggers, you want the function attached to it to use the children of its parent. This way, you can get the text fields for that row, rather than all text fields on the page.

 

Remember that when you create a new text field, you need to bind this action to it as well. My example only dealt with one's that were pre-existing, so I could just cycle through and do them all. You're going to have to do it after the creation to execute the function.

 

Now, since we are doing multiple calculations, we need to pass the element that activated so we know which row to calculate. Since you're using jQuery, you can just use $(this) when your $.keyup() function executes.

 

I would try to show more examples, but I don't want you to just copy and paste. I want you to understand what's going on, and how to do it rather than just asking for someone to do it for you each time you want to do something.

Share this post


Link to post
Share on other sites

just one example please....i'm too new to jquery ...just one

Share this post


Link to post
Share on other sites

I'm not going to give you one you can copy and paste though.

Demo: http://xaotique.no-ip.org/tmp/24/

 

HTML

<input type="button" id="add" value="Add Row" />
<div id="container" style="margin-top: 5px;"></div>

 

Just a button and container for our rows.

 

Javascript / jQuery

// Let page load
$(document).ready(function()
{
   // Add new row when button is clicked
   $("#add").click(function()
   {
       // Create the div (new row) and add its elements
       var div = $(document.createElement("div")).html('<input type="text" class="num" style="width: 100px;" /> <input type="text" class="num" style="width: 100px;" /> <span class="result"></span>');

       // Add div to the page
       $("#container").append(div);

       // When we type into text area
       div.find(".num").keyup(function()
       {
           // Starting total
           var total = 1;

           // Cycle the values and multiply the parsed number
           div.find(".num").each(function(i, elmn)
           {
               total *= Number(elmn.value);
           });

           // Show total
           div.find(".result").html(total);
       });

       // Trigger keyup when value changes (right-click paste wouldn't be typing)
       div.find(".num").change($(this).keyup());
   });
});

Share this post


Link to post
Share on other sites

cool thanks a lot !!!!

Will play with it tomorrow cause i'm in Spain and it's quite late here.

Stay tuned :happy-04:

Share this post


Link to post
Share on other sites

hi again,

this is my html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
 <meta http-equiv="content-type" content="text/html;charset=utf-8" />
 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
 <script type="text/javascript" src="../js/calculator2.js"></script>
</head>

<body>
 <input type="button" id="add" value="Add Row" />
 <div id="container" style="margin-top: 5px;"></div>
</body>
</html>

 

and this is my js

// Let page load
$(document).ready(function()
{
// Add new row when button is clicked
$("#add").click(function()
{
 // Create the div (new row) and add its elements
 var div = $(document.createElement("div")).html('<table width="901" align="center"><tr class="prototype"><form name="form" ><td bgcolor="#F8F8F8"<input type="ee" class="id" value="<?php echo $referencia?>" size="10" /></td><td bgcolor="#F8F8F8"><input  type="text"  id="descripcion[]" size="40"  /></td><td bgcolor="#F8F8F8"><input  type="text" class="num" style="width: 100px;"/></td><td nowrap bgcolor="#F8F8F8"><input type="text" class="num" style="width: 100px;"/><span class="blackTXT">€</span></td><td bgcolor="#F8F8F8"><span class="blackTXT">21%</span><td nowrap bgcolor="#F8F8F8"><span id="result"></span> <span class="blackTXT"><span class="result"></span> €</span><td bgcolor="#F8F8F8"><input type="button" id="remove" value="Remove Row" /> </form></tr></table> ');

 // Add div to the page
 $("#container").append(div);

 // When we type into text area
 div.find(".num").keyup(function()
 {
  // Starting total
  var total = 1;

  // Cycle the values and multiply the parsed number
  div.find(".num").each(function(i, elmn)
  {
   total *= Number(elmn.value);
  });

  // Show total
  div.find(".result").html(total);
 });

 // Trigger keyup when value changes (right-click paste wouldn't be typing)
 div.find(".num").change($(this).keyup());
});
// Remove button functionality
  $("#remove").click(function() {
   $(this).remove("div");

  });
 });

 

I can't get the remove button to remove a row....what is wrong?

 

thanks

Share this post


Link to post
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.