Sum up prices on selecting options - javascript

I'm trying to show the total price to the customer by each option that's selected:
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
});
It works, when check or uncheck the check boxes, total price will change. But the problem is if the submitted form has some validation errors on some inputs, the same page loads with given errors & all inputs that user entered before (check boxes too) but total price will not change since I'm using .change method.
As I'm not much familiar with related methods, Is there any method which will calculate total price on page ready and on input change?

You just have to simulate the change event like that :
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
}).trigger('change');
Edit
Since you want when atleast one is selected, use this instead :
$('input[type=checkbox]').change(function(){
var org = parseInt($('span#totalprice').text());
var chk = parseInt($(this).attr('price'));
total = this.checked ? (org + chk) : (org - chk);
$('span#totalprice').html(total);
}).filter(':checked').trigger('change');
.filter(':checked') should return nothing, therefor it will not trigger anything.

what about to recalculate every time the whole bunch of items?
e.g. create the function
function sumup_everything() {
var sum = 0;
$('input[type=checkbox]').each(/* here you calculate */);
/* setup sum value */
}
Then call it on input change and document.ready.
$(function() {
$('input[type=checkbox]').change(function(){ sumup_everything() });
sumup_everything();
});

Related

Javascript - clicking back in the browser and saving previously manipulated html elements

The website is a school, each school day has a set of 4 lessons with each lesson costing £7.50. When the user selects a day they go to a payment page where all 4 lessons are automatically selected as checkboxes, so the total cost is £30. The user can tick or untick each box to add or remove lessons which in turn changes the total amount on screen. The total amount is a html element with an id of #fullamount and a value of £30 :
<h6>Total Cost : <div id="fullamount" name="fullamount">£30</div></h6>
The problem I am having is that if the user proceeds to the external payment page(after selecting all lessons they want) but then decides to click on the back button to return to the original page - the checkboxes remain as they were but the total(#fullamount) returns back to the original state of £30 so if they had only selected 2 checkboxes it should be £15 but it shows up as £30, then if the user checks the other 2 checkboxes the total becomes £45.
Here is the Javascript:
$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#fullamount");
var $target = $("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("£", "") || 0);
var cur_total = +($total.html().replace("£", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("£" + cur_total);
$total.val(cur_total);
});
$('#myform').submit(function(e) {
e.preventDefault();
var $total = $("#fullamount");
var amount = $('#amount');
var thetotal = +($total.html().replace("£", "") || 0);
amount.val(thetotal);
this.submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm finding it quite hard to explain but I hope I made some sort of sense. Looking for a solution and struggling with it a bit. Any kind of help or advice would be really appreciated. Thanks.

jQuery traversing and finding textboxes

If I am looping through elements in a table - say a hidden field of class "pmtos" - how do I get a reference to the text field (input) within the same cell in the table?
jQuery is:
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this).val();
//
//find text box in same cell - and populate with some value
//
//
});
Thank you for any guidance in getting this working.
Mark
Here's a solution to the question before it was edited (as requested):
$('#allocate').click(function () {
var recd = parseFloat( $('#pmtRecd').val() );
$('input.pmtallocated').each(function() {
var value = parseFloat( $(this).parent().prev().text() );
this.value = (recd >= value) ? value : recd;
recd = recd - this.value;
if (recd == 0) {
return false;
}
});
});
Note: This doesn't rely on the hidden input. It takes the text from the td in the second column.
Here's the fiddle
To answer the question post-edit
You can use siblings('.pmtallocated') or prev('.pmtallocated') to get the input. Using siblings() would probably be the better of the two as it doesn't rely on pmtallocated coming directly before pmtos in the markup:
$(this).siblings('.pmtallocated').val()
Try
// Loop through each hidden field, which holds the outstanding amount
$(".pmtos").each(function () {
var os = $(this);
var cell = os.parent(); // gets the parent, i.e. the table cell
var input = cell.find('input')[0];
});
You could use $(this).closest('input')
Check this out. may works for you.
$(".pmtos").each(function () {
var os = $(this).val();
var input = $(this).closest('td').find('input[type=text]');
});

textbox keyup event not working properly

I am using following code to update one textbox value txtUnitPrice based on other textbox txtQuantity ,both can be generated dynamically which is done.
//update unitprice based on quantity of product and tax applied
$('input').live('keyup', function () {
var inputId = $(this).attr('id'); //get textbox txtQuantity id
var rowNum = parseInt(/txtQuantity(\d+)/.exec(inputId)[1], 10); //get row id
var productValue = $("#ddlProduct" + rowNum).val();
var taxValue = $("#ddlTax" + rowNum).val();
var unitPriceValue = $("#txtUnitPrice" + rowNum).val();
var quantityValue = $("#txtQuantity" + rowNum).val();
if ((quantityValue != " ") && (quantityValue > 0)) {
$("#txtUnitPrice" + rowNum).val(unitPriceValue * quantityValue);
}
else {
$("#txtUnitPrice" + rowNum).val(unitPriceValue);
}
});
Now problem arising in the code above is that when I even moving cursor forward or backward in the textbox txtQuantity then the value for txtUnitPrice is changing becuase which this event 'keyup' is firing and hence whole code is executed with the existing txtunitprice value and multiplies this again with the existing txtquantity which I dont' want Please can anyone help me regarding this . Thanks
Just add a check to ignore the cursor movements like shown below
$('input').live('keyup', function (e) {
if([37, 38, 39, 40].indexOf(e.which)){
return false;//do nothing because the cursor keys have been pressed
}
//the rest of your code
});

How the select the multiple Table data as per selected checkbox?

There is one data table with two rows, as per below image
When user click on 2bit it should highlight that TD in that column only. I achieved this using jQuery for one check box selection, but when multiple check box selection like 2 and 4 it should highlight both the TD.
http://jsbin.com/exazoh/edit#preview working example for single value highlight.
Code: http://jsbin.com/exazoh/2/edit
Try the following function:
jQuery(function() {
// on change of an input with a name starting with "bit-select"...
jQuery('input[name^="bit-select"]').change(function(){
var checked = this.checked,
val = this.value,
column = $(this).closest("th").index() + 1;
// for each td in the current column
jQuery("#tableData tr.data td:nth-child(" +
column + ")").each(function() {
var $td = $(this);
// does the current td match the checkbox?
if ($td.text() == val) {
if (checked)
$td.addClass("jquery-colorBG-highLight");
else
$td.removeClass("jquery-colorBG-highLight");
}
});
});
});
I had to add the value attributes to the second set of checkboxes.
Working demo: http://jsbin.com/exazoh/4/edit#preview
Or the short version, since I notice you were using .filter() originally:
jQuery(function() {
jQuery('input[name^="bit-select"]').change(function(){
var method = this.checked ? "addClass" : "removeClass",
val = this.value;
jQuery("#tableData tr.data td:nth-child("+($(this).closest("th").index()+1)+")")
.filter(function(){return $(this).text()==val;})[method]("jquery-colorBG-highLight");
});
});
Demo: http://jsbin.com/exazoh/5/edit

Jquery:Sum values of checkbox on same row to textfield on same row

I have some checkboxes with values which need sum up. When the checkboxes are checked the values get added in an array and displayed. Here is a demo link: http://jsfiddle.net/maxwellpayne/gKWmB/
However when I go to a new row it continues summing my values instead of starting afresh emptying the array on row change.The HTML code is long so please view it at the link provided.
Here is the jquery code summing them up:
var total_array = new Array();
var total_amount = 0;
$("#dailyexpense input[type=checkbox]:checked ").live('change', function() {
var check_id = $(this).attr('id');
var valu = $(this).val();
$("#tdtotals input[type=text]").each(function() {
totals_id = $(this).attr('id');
if (totals_id == check_id) {
total_array.push(valu);
total_amount = eval(total_array.join('+')).toFixed(2);
$(this).val(total_amount);
}
});
});
All help will be appreciated
PS: However is editing the code in jsfiddle and distorting everything, stop it.
Try this:
http://jsfiddle.net/gKWmB/3/
Basically we rethink the structure. If a checkbox value changes we get its parent row. Then we find all checkboxes in that row. Finally we total them and display.
//watch checkboxes
$('tr input[type=checkbox]').change( function(){
var total = 0;
//total all sibling checkboxes
$(this).parents('tr').find('input[type=checkbox]:checked').each( function() {
total += parseInt($(this).val());
});
//display the result
$(this).parents('tr').find('input[type=text]:last').val(total);
});

Categories

Resources