Jump to content


Photo

Please Help With Js Calculation


  • Please log in to reply
39 replies to this topic

#1 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 12:34 PM

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

Edited by lingo5, 04 December 2012 - 12:36 PM.


#2 StefanRSA

StefanRSA

    Advanced Member

  • Members
  • PipPipPip
  • 277 posts
  • LocationSouth Africa... In cyberspace!

Posted 04 December 2012 - 01:05 PM

Lingo,

I have a complete working script in my previous post.
Am sure it will help.

http://forums.phpfreaks.com/topic/270366-javascript-calculation-help-needed-onselect/
Howzit! Interested in Free Advertising? Start by linking your website on the Howzit! Website directory...
http://www.howzituk.com
http://www.howzit.co.za

#3 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 01:33 PM

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

#4 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 02:09 PM

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) <img src='http://forums.phpfreaks.com/public/style_emoticons/<#EMO_DIR#>/tease-02.gif' class='bbc_emoticon' alt=':P' />
    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);

Edited by Xaotique, 04 December 2012 - 02:13 PM.


#5 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 02:36 PM

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) <img src='http://forums.phpfreaks.com/public/style_emoticons/<#EMO_DIR#>/tease-02.gif' class='bbc_emoticon' alt=':P' />
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);


#6 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 02:40 PM

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

#7 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 02:41 PM

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.

#8 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 02:55 PM

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

#9 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 02:57 PM

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.

#10 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 03:08 PM

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

#11 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 03:13 PM

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").

#12 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 03:32 PM

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&oacute;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">&euro;</span></td>
	   <td bgcolor="#F8F8F8"><span class="blackTXT">21%</span>
		 <td nowrap bgcolor="#F8F8F8"><span id="result"></span> <span class="blackTXT">&euro;</span>
	   <td bgcolor="#F8F8F8"><button class="remove">Remove</button></form>
	 </tr>
  </table>
</body>
</html>


#13 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 03:38 PM

Link me to it?

#14 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 04:00 PM

here you are http://www.redbook.e...tor/index-2.php

#15 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 04:03 PM

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.

#16 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 04:04 PM

ooops...sorry

#17 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 04:06 PM

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.

#18 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 04:09 PM

:confused: sorry

#19 Xaotique

Xaotique

    Advanced Member

  • Members
  • PipPipPip
  • 564 posts
  • LocationPennsylvania, United States
  • Age:22

Posted 04 December 2012 - 04:15 PM

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.

#20 lingo5

lingo5

    Advanced Member

  • Members
  • PipPipPip
  • 406 posts
  • LocationSpain
  • Age:20

Posted 04 December 2012 - 04:19 PM

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




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com