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
Calculating values using jQuery
Moderator: General Moderators
- novice4eva
- Forum Contributor
- Posts: 327
- Joined: Thu Mar 29, 2007 3:48 am
- Location: Nepal
Re: Calculating values using jQuery
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:
obviously you would need to call the javascript function in onBlur event, and i bet you already know how 
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>
Re: Calculating values using jQuery
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.