I have this code but is not working properly.
The idea is that every input has a value and sum or subtract its value from the total price depending if you click up or down.
Right now is just adding and adding and adding like crazy.
Thank you very much.
the JS:
$( document ).ready(function() {
$(".quantity").each(function(){
$(this).change(function(){
var quantity = ($(this).val());
var ammount = ($(this).attr("data-price"));
var price = $(this).closest(".bookSection").find(".item_price").html();
var subtotal = ammount * quantity;
var total = parseInt(subtotal) + parseInt(price);
$(this).closest(".bookSection").find(".item_price").html(total);
});
});
});
here the example:
http://jsbin.com/tolequyobi/1/edit?html,js,output
Instead of trying to use the .item_price just calculate it from the start. If not you will need to store the old value to know if you need to add or subtract.
You can do something like this
$('.quantity').change(function(){ // check change on the inputs
var total = 0; // set the total to 0
$(this).parent().find('.quantity').each(function() { // loop on all the items thats in this block
total += parseInt($(this).attr('data-price')) * parseInt($(this).val()); // add to the total their value
});
$(this).parent().find(".item_price").html(total); // and then add it to your html
});
How about recomputing the total from scratch whenever the quantity changes, instead of trying to keep a running total that you have to maintain?
$( document ).ready(function() {
var price = 0;
$(".quantity").each(function(){
$(this).change(function(){
var total = computeTotal($(this).closest(".bookSection"));
$(this).closest(".bookSection").find(".item_price").html(total);
});
});
});
function computeTotal(bookSection){
var total=0;
bookSection.children('.quantity').each(function(item){
total += $(this).val() * $(this).attr("data-price");
});
return total;
http://jsbin.com/rimubocijo/edit?html,js,output
Related
I have an existing document that has pre existing pricing. So on the page I have a bunch of elements for example price here with each one having different pricing of course.
How can I write a jquery/javascript script to take each of those prices and divide them by 24 and then append a p tag that shows that calculation, this should happen on page load.
so far i have this, just testing it on click but it gives me the same answer for each, which is the very first occurrence of the price divided by 24.
for ex if they price is 1600, or 500, or 100000 the answer it gives me is always based on 1600.
$(".button").click(function () {
var value = $('.price').text();
var price = parseFloat(value)/24;
$('.price').append('<p>' + price + '</p>');
});
Can someone help please?
Thank you :)
In the above code, your use of the text() method selects only the first element with the class price.
You need to loop over all the elements with the class price.
$(".button").click(function () {
$('.price').each(function(index, el) {
var price = parseFloat($(el).text())/24;
$(el).append('<p>' + price + '</p>');
});
});
This is because of var value = $('.price').text(); it selects the first price it finds.
You should use a variable in the event handler to get access to the item that was clicked on. Then get the price from that.
Assuming the button has a descendant with a price class :
$(".button").click(function (e) {
var value = $(event.currenttarget).find(".price")
...
}
I think something like the following implementation should work:
document.querySelectorAll('.button').forEach(element => {
const priceElement = element.querySelector('.price');
const price = parseFloat(priceElement.textContent) / 24;
const childElement = document.createElement('p');
childElement.textContent = price;
priceElement.appendChild(childElement);
});
$(".button").click(function () {
$('.price').each(function(p){
$('.price')[p].innerHTML = $('.price')[p].innerHTML/24});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='price button'>240</div>
<div class='price'>480</div>
i just want to fetch the value from 3 rows using jquery and calculate then displays to bottom field
You can use jQuery change event (docs).
$( "input.amount" ).change(function() {
var amount = $( this ).val();
// calculations:
// var total = amount * ...
$('#total').val(total);
// ...
});
I need to add and delete the number "7" based on a user checking a checkbox and then display that number on the page:
var theTotal = 0;
$("#highlightChk").change(function() {
var ishchecked= $(this).is(':checked');
if(!ishchecked) theTotal -= 7;
if(ishchecked) theTotal += 7;
});
$('#total').text(theTotal);
When I display the code it is "0" even when I check the checkbox. What am I doing wrong?
Place an initial value in #total and each time an operation is being done read the value and parse it and add to or subtract from it. The #total element has to be updated within the change event handler.
$(function() {
$("#highlightChk").on('change', function() {
//READ & PARSE existing value
var total = +$('#total').text();
//INC-/DECREMENT value accordingly
total += this.checked ? 7 : -7;
//UPDATE DOM with new value
$('#total').text( total ); //<<--- BELONGS INSIDE
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="highlight" id="highlightChk"/> Highlight<br><br>
Total: <div id="total">0</div>
You need to put the $('#total').text(theTotal); inside the change method
$("#highlightChk").change(function () {
var theTotal = 0;
var ishchecked = $(this).is(':checked');
if (!ishchecked) theTotal -= 7;
else theTotal += 7;
$('#total').text(theTotal);
});
Since theTotal as a global variable is always 0, but when it's inside the local scope of the jquery .change() method you will always get the correct changed value.
FIDDLE DEMO #1
You can also achieve the same result with less code like:-
$("#highlightChk").change(function () {
$('#total').text(this.checked ? 7 : 0);
});
FIDDLE DEMO #2
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();
});
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);
});