How to reflect a calculation from one field to another - javascript

I'm very new to JavaScript and I have an assignment that I'm unable to resolve. So I have a table with five fields and I need to calculate the total for a month, then automatically generate the yearly total in a different cell. I got to make the total work for the month but I have no idea how to reflect that in the year cells. Any help will be much appreciated. Thanks a lot for your time :)
Here's my code:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function update() {
var a = +document.forms['calc'].elements['fieldOne'].value,
b = +document.forms['calc'].elements['fieldTwo'].value,
c = +document.forms['calc'].elements['fieldThree'].value,
d = +document.forms['calc'].elements['fieldFour'].value,
e = +document.forms['calc'].elements['fieldFive'].value,
fieldTotal = ((b-d)*a)*c;
document.forms['calc'].elements['fieldTotal'].value = fieldTotal;
return false;
}
function update2() {
var f = +document.forms['calc'].elements['field6'].value,
g = +document.forms['calc'].elements['field7'].value,
h = +document.forms['calc'].elements['field8'].value,
i = +document.forms['calc'].elements['fieldFour'].value,
j = +document.forms['calc'].elements['fieldFive*12'].value,
field9=fieldFour;
field10=fieldFive*12;
fieldTotal2=fieldTotal*12;
document.write('fieldTotal2');
document.write('field9');
document.write('field10');
return false;
}
</script>
</head>
<body>
<form name="calc" action="#">
<table width="600" border="1">
<tr>
<td colspan="2"> </td>
<td width="63">Month</td>
<td width="109">Year</td>
</tr>
<tr>
<td colspan="2">Field1</td>
<td><input type="text" name="fieldOne" id="fieldOne" size="15" value="5,000" /></td>
<td><input type="text" name="field6" id="field6" size="15" value="60,000"/></td>
</tr>
<tr>
<td colspan="2">Field2</td>
<td><input type="text" name="fieldTwo" id="fieldTwo" value="3.0" size="15" /></td>
<td><input type="text" name="field7" id="field7" value="3.0" size="15" /></td>
</tr>
<tr>
<td colspan="2">Field3</td>
<td><input type="text" name="fieldThree" id="fieldThree" size="15" value="$350"/></td>
<td><input type="text" name="field8" id="field8" size="15" value="$350"/></td>
</tr>
<tr>
<td colspan="2">Field4</td>
<td><input type="text" name="fieldFour" id="fieldFour" value="1.5" size="15" /></td>
<td><input type="number" name="field9" id="field9" value="1.5" size="15" /></td>
</tr>
<tr>
<td colspan="2">Filed5</td>
<td><input type="text" name="fieldFive" id="fieldFive" size="15" value="75"/></td>
<td><input type="text" name="field10" id="field10" size="15" /></td>
</tr>
<tr>
<td width="137">Total</td>
<td width="83"><input type="button" value="Calculate" onClick="update();return false;" /></td>
<td><input type="text" name="fieldTotal" id="fieldTotal" size="15" readonly /></td>
<td><input type="text" name="fieldTotal2" id="fieldTotal2" size="15" readonly /></td>
</tr>
</table>
</form>
</body>

Based on what you described I think this should work for you.
Demo
function update() {
var frmEles = document.forms.calc.elements,
a = frmEles.fieldOne.value.replace(',',''), //Remove comma
b = frmEles.fieldTwo.value,
c = frmEles.fieldThree.value.replace('$',''), //Remove Dollar sign
d = frmEles.fieldFour.value,
e = frmEles.fieldFive.value,
fieldTotal = ((b-d)*a)*c;
//Total for the month
frmEles.fieldTotal.value = formatNumber(fieldTotal);
//Calculations for the year
frmEles.field6.value = formatNumber(a * 12);
frmEles.field7.value = formatNumber(b * 12);
frmEles.field8.value = '$' + formatNumber(c * 12); //Add back dollar sign
frmEles.field9.value = formatNumber(d * 12);
frmEles.field10.value = formatNumber(e * 12);
frmEles.fieldTotal2.value = formatNumber(fieldTotal * 12);
return false;
}
//Format the numbers with commas.
function formatNumber(n){
return n.toLocaleString();
}

Related

How do I round off the result? [duplicate]

This question already has answers here:
Gaussian/banker's rounding in JavaScript
(9 answers)
Closed 3 years ago.
<script >
function sum() {
var txtFirstNumberValue = document.getElementById('studentenrolled').value;
var txtSecondNumberValue = document.getElementById('classsize').value;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('nooftut').value = result;
}
}
</script>
<tr>
<td><label for="studentenrolled">Student Enrolled</label> </td>
<td> <input type="text" name="studentenrolled" id="studentenrolled" value="<?php echo $row['studentenrolled']; ?> " /></td>
</tr>
<tr>
<td><label for="classsize">Class Size</label> </td>
<td> <input type="text" id="classsize" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="nooftut">No Of Tutorial</label> </td>
<td> <input type="text" id="nooftut" disabled="disabled" /></td>
</tr>
How to I round up or down the results in "nooftut"
Calculation : studentenrolled / class size = nooftut
As studentenrolled is pulled from the db, I'm not able to round up or down
Try Math.round()
function sum() {
var txtFirstNumberValue = document.getElementById('studentenrolled').value;
var txtSecondNumberValue = document.getElementById('classsize').value;
var result = parseInt(txtFirstNumberValue) / parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('nooftut').value = Math.round(result);
}
}
<tr>
<td><label for="studentenrolled">Student Enrolled</label> </td>
<td> <input type="text" name="studentenrolled" id="studentenrolled" value=" " /></td>
</tr>
<tr>
<td><label for="classsize">Class Size</label> </td>
<td> <input type="text" id="classsize" onkeyup="sum();" /></td>
</tr>
<tr>
<td><label for="nooftut">No Of Tutorial</label> </td>
<td> <input type="text" id="nooftut" disabled="disabled" /></td>
</tr>
+1.5 => +1.0 using Math.floor() (To round down)
-1.5 => -1.0 using Math.ceil() (To round up)
or just Math.round(0.9) => 1

how to add array values in text box

I have three text box that given as an array, I want to add two text box and get a result in the third text box as shown in below.
<tbody>
<?php
$i=1;
foreach ($sub as $row)
{
?>
<tr>
<td><?php echo $i++;?>
</td>
<td> <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
<td><input type="text" name="mark-1[]" value="" id="mark1"></td>
<td><input type="text" name="mark-2[]" value="" id="mark2"></td>
<td><input type="text" name="total-mark[]" value="" id="totmark" onclick="add_number()"></td>
</tr>
<?php } ?>
<tr>
<th colspan="4">Total Mark</th>
<td></td></tr>
</tbody>
i have used the below script and its running but getting a result in the first loop
<script type="text/javascript">
function add_number() {
var first_number = parseInt(document.getElementById("mark1").value);
var second_number = parseInt(document.getElementById("mark2").value);
var result = first_number + second_number;
document.getElementById("totmark").value = result;
}
</script>
please help us get an answer
html
<tbody>
<?php
$i=1;
$k=1;
foreach ($sub as $row)
{ $k++;
?>
<tr>
<td><?php echo $i++;?>
</td>
<td> <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
<td><input type="text" name="mark-1[]" value="" id="mark1-<?php echo $k;?>"></td>
<td><input type="text" name="mark-2[]" value="" id="mark2-<?php echo $k;?>"></td>
<td><input type="text" name="total-mark[]" value="" id="totmark-<?php echo $k;?>" onclick="add_number(<?php echo $k;?>)"></td>
</tr>
<?php } ?>
<tr>
<th colspan="4">Total Mark</th>
<td></td></tr>
</tbody>
Script
<script type="text/javascript">
function add_number(k) {
var first_number = parseInt(document.getElementById("mark1-"+k).value);
var second_number = parseInt(document.getElementById("mark2-"+k).value);
var result = first_number + second_number;
document.getElementById("totmark-"+k).value = result;
}
</script>
The problem is the repeated IDs for each iteration, mark1, mar2, mark1, mark2, and so on. The function getElementById is returning the first element.
An alternative is to use the function closest('tr') and then find by name [name="mark-1[]"] and [name="mark-2[]"]. Then find the field to store the result using this .querySelector('[name="total-mark[]"]').
Finally, using the function addEventListener you can bind the event click to the whole set of elements [name="total-mark[]"].
document.querySelectorAll('[name="total-mark[]"]').forEach(function(elem) {
elem.addEventListener('click', add_number);
});
function add_number() {
var tr = this.closest('tr');
var first_number = tr.querySelector('[name="mark-1[]"]').value;
var second_number = tr.querySelector('[name="mark-2[]"]').value;
var result = Number(first_number) + Number(second_number);
this.value = result;
}
<table>
<tbody>
<tr>
<td><input type="text" name="mark-1[]" value="" ></td>
<td><input type="text" name="mark-2[]" value="" ></td>
<td><input type="text" name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
<tr>
<td><input type="text" name="mark-1[]" value="" ></td>
<td><input type="text" name="mark-2[]" value="" ></td>
<td><input type="text" name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
</tbody>
</table>
A recommendation is using the current index from the PHP variable $i and add specific IDs to every field, that way you will be able to get the elements directly. For example, the two fields would have these IDs: mark-1-1[], mark-1-2[] and mark-2-1[], mark-2-2[], and so on.
This approach uses the attribute dataset.
document.querySelectorAll('[name="total-mark[]"]').forEach(function(elem) {
elem.addEventListener('click', add_number);
});
function add_number() {
var field = this.dataset.field;
var first_number = document.getElementById('mark-1-' + field + '[]').value;
var second_number = document.getElementById('mark-2-' + field + '[]').value;
var result = Number(first_number) + Number(second_number);
this.value = result;
}
<table>
<tbody>
<tr>
<td><input type="text" id="mark-1-1[]" value="" ></td>
<td><input type="text" id="mark-2-1[]" value="" ></td>
<td><input type="text" data-field='1' name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
<tr>
<td><input type="text" id="mark-1-2[]" value="" ></td>
<td><input type="text" id="mark-2-2[]" value="" ></td>
<td><input type="text" data-field='2' name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
</tbody>
</table>

jQuery- Dynamically multiply input values of table rows with different id

Dynamically adding table rows using below code. User ID is appended for input id.
var selResId = jQuery('#grid').jqGrid('getGridParam', 'selarrrow');
var j=1;
for (var i=0, il=selResId.length; i < il; i++) {
var name = jQuery('#grid').jqGrid('getCell', selResId[i], 'USER_NAME');
$('#addr'+j).html("<td style='text-align:center;'>"+name+"</td><td><input id='hours_"+selResId[i]+"' value='80' type='text' readonly /></td><td><input id='rate_"+selResId[i]+"' type='text' /></td><td><input name='markup_"+selResId[i]+"' type='text'/></td><td><input name='totalcost_"+selResId[i]+"' type='text' readonly></td>");
$('#resource_table').append('<tr id="addr'+(j+1)+'"></tr>');
j++;
}
}
HTML Generated
<tr id="addr1">
<td>John Doe</td>
<td><input type="text" readonly="" value="80" id="hours_10"></td>
<td><input type="text" value="" id="rate_10"></td>
<td><input type="text" value="" id="markup_10"></td>
<td><input type="text" readonly="" value="" id="totalcost_10"></td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td><input type="text" readonly="" value="80" id="hours_11"></td>
<td><input type="text" value="" id="rate_11"></td>
<td><input type="text" value="" id="markup_11"></td>
<td><input type="text" readonly="" value="" id="totalcost_11"></td>
</tr>
How do I multiply input values for hours, rate and markup and show it under total cost input using below formula. The event could be keyup.
Initially, totalcost = hours * rate
Case 1: If markup (%) > 0, for eg: 10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) + markup_cost
Case 2: If markup (%) < 0, for eg: -10%, then markup_cost = (hours * rate * markup) / 100
totalcost = (hours * rate) - markup_cost
Try to use starts with selector like,
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
$(function(){
function setTotalCost(n){
var h=Number($('#hours_'+n).val()),
m=Number($('#markup_'+n).val()), // taking 0 if empty
r=Number($('#rate_'+n).val());
$('#totalcost_'+n).val(h*m*r);
}
$('[id^="rate_"]').on('keyup',function(){
var n = this.id.replace('rate_','');// get the number
setTotalCost(n);
});
$('[id^="markup_"]').on('keyup',function(){
var n = this.id.replace('markup_','');// get the number
setTotalCost(n);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="addr1">
<td>John Doe</td>
<td>
<input type="text" readonly="" value="80" id="hours_10">
</td>
<td>
<input type="text" value="" id="rate_10">
</td>
<td>
<input type="text" value="" id="markup_10">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_10">
</td>
</tr>
<tr id="addr2">
<td>Foo User</td>
<td>
<input type="text" readonly="" value="80" id="hours_11">
</td>
<td>
<input type="text" value="" id="rate_11">
</td>
<td>
<input type="text" value="" id="markup_11">
</td>
<td>
<input type="text" readonly="" value="" id="totalcost_11">
</td>
</tr>
</table>

Using the same jQuery in multiple operations

I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});

calculate sub total based on calculations

I am trying to calculate the "sub_total" field based on:
"total_full" + "total_half". however the javascript which i tried is not working. the result of sub_total is displaying as "0".
How can I improve my javascript "calculate sub total" to allow me to add "total_full" and "total_half" together? ( I will then also implement the sub_total calculation to include "total_single", "total_double", and "total_projector" as well when I can get the calculation right.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Conference Form</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jqueryui.js"></script>
<link href="style.css" rel="stylesheet" type="text/css"/>
<link href="css/jqueryui.css" rel="stylesheet" type="text/css" />
<body>
<div id="wrapper">
<div id="header"></div>
<table width="899" border="1" align="left" cellpadding="1">
<form action="" method="get" name="myform">
<tr>
<td width="258"><label>Company Name</label></td>
<td width="249"><input type="text" name="companyname" id="companyname" /></td>
<td width="27"> </td>
<td width="186">Enquiry Date</td>
<td width="145"><input type="text" name="enquiry_date" id="enquiry_date" class="datepicker" /></td>
</tr>
<tr>
<td>Conference Date In</td>
<td><input type="text" name="conference_date_in" id="conference_date_in" class="datepicker" /></td>
<td> </td>
<td>Conference Date Out</td>
<td><input type="text" name="conference_date_out" id="conference_date_out" class="datepicker" /></td>
</tr>
<tr>
<td>Total Days</td>
<td><input type="text" name="total_days" id="total_days" /></td>
</tr>
<tr>
<td>Number of Delegates</td>
<td><input type="text" name="no_of_delegates" id="no_of_delegates" /></td>
</tr>
<tr>
<td>Accommodation:</td>
<tr>
<td><p>Check in Date</p></td>
<td><input type="text" name="check_in_date" id="check_in_date" class="datepicker" /></td>
<td><p>Check out Date</p></td>
<td><p>
<input type="text" name="check_out_date" id="check_out_date" class="datepicker" />
</p></td>
</tr>
<tr>
<td>Total Days Accommodation</td>
<td><input type="text" name="total_days_acc" id="total_days_acc" /></td>
</tr>
<tr>
<td><strong>Contact Details</strong></td>
</tr>
<tr>
<td>Contact Person</td>
<td><input type="text" name="contact_person" id="contact_person" /></td>
</tr>
<tr>
<td>Telephone Number</td>
<td><input type="text" name="tel_no" id="tel_no" /></td>
<td> </td>
<td>Fax Number</td>
<td><input type="text" name="fax_no" id="fax_no" /></td>
</tr>
<tr>
<td>Cell Number</td>
<td><input type="text" name="cell_no" id="cell_no" /></td>
<td> </td>
<td>Email</td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Full Day Conference # R260 p/p</td>
<td><input type="text" name="full_day" id="full_day" />
Full Days</td>
<td> </td>
<td>Total Cost Full Day</td>
<td><input type="text" name="total_full" id="total_full" readonly="readonly" /></td>
</tr>
<tr>
<td>Half Day Conference # R240 p/p</td>
<td><input type="text" name="half_day" id="half_day" />
Half Days</td>
<td> </td>
<td>Total Cost Half Day</td>
<td><input type="text" name="total_half" id="total_half" readonly="readonly" /></td>
</tr>
<tr>
<td>Single Rooms # R480 p/p</td>
<td><input type="text" name="single_rooms" id="single_rooms" />
Guests</td>
<td> </td>
<td>Total Cost Single Rooms</td>
<td><input name="total_single" type="text" id="total_single" readonly="readonly" /></td>
</tr>
<tr>
<td>Double / Twin Rooms # R360 p/p/s</td>
<td><input type="text" name="double_rooms" id="double_rooms" />
Guests</td>
<td> </td>
<td>Total Cost Double / Twin</td>
<td><input name="total_double" type="text" id="total_double" readonly="readonly" /></td>
</tr>
<tr>
<td>Data Projector # R400 rental p/day</td>
<td><input type="text" name="data_projector" id="data_projector" />
Days</td>
<td> </td>
<td>Total Cost Projector Rental</td>
<td><input name="total_projector" type="text" id="total_projector" readonly="readonly" /></td>
</tr>
<tr>
<td>Sub Total</td>
<td><input name="sub_total" type="text" id="sub_total" readonly="readonly" /></td>
</tr>
<tr>
<td height="23"> </td>
</tr>
</form>
</table>
</div>
<div id="hideme">
Hello Hideme
</div>
</body>
</html>
JAVASCRIPT
<script type="text/javascript">
//Datepicker
$(function() {
$(".datepicker").datepicker({ minDate: -0, maxDate: "+100M +10D",dateFormat: 'dd-mm-yy'})
({
changeMonth: true,
changeYear: true,
});
});
//Datepicker Enquiry Date Set to Today
var enquiry_date = $.datepicker.formatDate('dd-mm-yy', new Date());
document.getElementById('enquiry_date').value = enquiry_date;
//Datepicker Conference in / out
var calcDate = function() {
var start = $('#conference_date_in').datepicker('getDate');
var end = $('#conference_date_out').datepicker('getDate');
var days = (end - start) / 1000 / 60 / 60 / 24 + 1;
if(days==0) {days=1
}
if( days >= 0 ) {
document.getElementById('total_days').value = days;
}
}
$('#conference_date_out').change(calcDate);
$('#conference_date_in').change(calcDate);
//Datepicker Check in / Out Accommodation
var calcDateAcc = function() {
var startacc = $('#check_in_date').datepicker('getDate');
var endacc = $('#check_out_date').datepicker('getDate');
var daysacc = (endacc - startacc) / 1000 / 60 / 60 / 24;
if(daysacc==0) daysacc=1
if( daysacc >= 0 ) {
document.getElementById('total_days_acc').value = daysacc;
}
}
$('#check_in_date').change(calcDateAcc);
$('#check_out_date').change(calcDateAcc);
//Calculate Total Cost FullDay Conference
function calculateFull()
{
var fulldays = parseInt(document.getElementById("full_day").value);
var no_of_delegates = parseInt(document.getElementById("no_of_delegates").value);
var fullprice = 260;
var resultfull = fulldays * no_of_delegates * fullprice;
document.getElementById("total_full").value = resultfull;
}
$('#full_day').change(calculateFull).keyup(calculateFull);
//Calculate Half Day conference total
function calculateHalf()
{
var halfdays = parseInt(document.getElementById("half_day").value);
var no_of_delegates = parseInt(document.getElementById("no_of_delegates").value);
var halfprice = 240;
var resulthalf = halfdays * no_of_delegates * halfprice;
document.getElementById("total_half").value = resulthalf;
}
$('#half_day').change(calculateHalf).keyup(calculateHalf);
//Calculate Total Cost Single Rooms
function calculateSingle()
{
var single_rooms = parseInt(document.getElementById("single_rooms").value);
var total_days_acc = parseInt(document.getElementById("total_days_acc").value);
var single_rooms_price = 480;
var resultsingle = single_rooms * total_days_acc * single_rooms_price;
document.getElementById("total_single").value = isNaN(resultsingle) ? 0 : resultsingle;
}
$('#single_rooms').change(calculateSingle).keyup(calculateSingle);
$('#check_in_date').change(calculateSingle);
$('#check_out_date').change(calculateSingle);
//Calculate Total Cost Double / Twin Rooms
function calculateDouble()
{
var double_rooms = parseInt(document.getElementById("double_rooms").value);
var total_days_acc = parseInt(document.getElementById("total_days_acc").value);
var double_rooms_price = 360;
var resultdouble = double_rooms * total_days_acc * double_rooms_price;
document.getElementById("total_double").value = isNaN(resultdouble) ? 0 : resultdouble;
}
$('#double_rooms').change(calculateDouble).keyup(calculateDouble);
$('#check_in_date').change(calculateDouble);
$('#check_out_date').change(calculateDouble);
//Calculate Total Cost Date Projector
function calculateProjector()
{
var data_projector = parseInt(document.getElementById("data_projector").value);
var data_projector_price = 400;
var resultdata = data_projector * data_projector_price;
document.getElementById("total_projector").value = isNaN(resultdata) ? 0 : resultdata;
}
$('#data_projector').change(calculateProjector).keyup(calculateProjector);
//Calculate Sub Total
function calculateSubTotal()
{
var SubTotal = total_full + total_half;
document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}
$('#data_projector').change(calculateSubTotal).keyup(calculateSubTotal);
//Hide me Testing
$("#full_day").keyup(function(){
if ($('#full_day').val() == "1") {
$("#hideme").show("fast"); //Slide Down Effect
}
else {
$("#hideme").hide("fast"); //Slide Up Effect
}
});
</script>
Does this do what you want :
//Calculate Sub Total
function calculateSubTotal()
{
var SubTotal = +total_full.value + +total_half.value;
document.getElementById("sub_total").value = isNaN(SubTotal) ? 0 : SubTotal;
}
document.getElementById("total_half").onchange = calculateSubTotal;
document.getElementById("total_half").onkeyup = calculateSubTotal;
Note the use of unary + and .value when getting the values entered in total_full and total_half. Also the setting the of event handlers.
Try it out here : http://jsfiddle.net/jstoolsmith/ue62p/

Categories

Resources