Calculating values using jQuery

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
playaz
Forum Newbie
Posts: 4
Joined: Tue Jul 19, 2005 8:02 pm

Calculating values using jQuery

Post by playaz »

Hi guys,

I am building a form that will automatically calculate the values entered by a user ideally using jQuery/javascript, i am not sure how to do this but have a general idea of the logic required (i am no expert so feel free to correct me) - I have created a dummy image to help explain what I am trying to do.

http://img399.imageshack.us/my.php?image=tablehw2.png

I have a single form, which has two tables each with form fields that automatically calculate the total amount for each table provided it has been selected.
Using jQuery - I would expect the logic to be something like -
i) Find the table element
ii) Find all the text fields within the table that have a value
iii) Add these together and display in the 'total' form field within the last row of each table

While i'm ok on the PHP, javascript is something I still get confused with at times - I would appreciate any help on doing this, and if possible a quick overview to help me learn from the code.

Thanks in advance

Gaz
User avatar
novice4eva
Forum Contributor
Posts: 327
Joined: Thu Mar 29, 2007 3:48 am
Location: Nepal

Re: Calculating values using jQuery

Post by novice4eva »

in javascript you can access those values by following this format
document.formName.fieldName.value
OR by id as
document.getElementById('fieldId').value

Example would be:

Code: Select all

 
<form name="test">
<input type="text" name="field1" id="field1" value="1">
<input type="text" name="field2" id="field2" value="2">
<input type="text" name="total" id="total">
</form>
<script>
function summ()
{
var sum=parseInt(document.test.field1.value)+parseInt(document.test.field2.value);
document.getElementById('total').value = sum;
}
 
summ();
</script>
 
obviously you would need to call the javascript function in onBlur event, and i bet you already know how :D
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Calculating values using jQuery

Post by pickle »

Here's some jQuery:

Code: Select all

//instantiate the total variable
var total=0;
 
//iterate through all input elements of type "text" inside the element identified by id "tableID"
$("#tableID input:text").each(function(){
  //if the current textfield has a value
  if($(this).val().length > 0){
    //add it to the total
    total += $(this).val();
  }
}
//display your total
$("element-to-populate").val(total);
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply