Calculating multiple items - javascript

I am trying to find the markup of items based on the price we purchase the item minus the price we charge and divide that by the price sell it for times 100 Anyways I'm trying to this for multiple items onblur but for some reason i it comes up with NaN. I am bad at explaining things here's the example of what I want to do.
<script language="javascript">
function calculatemarkup(){
Example of the entry
if(isNaN(document.TOTALS.CostFOBfact4.value) || document.TOTALS.CostFOBfact4.value==""){ 
var text8 = 0; 
}else{ 
var text8 = parseFloat(document.TOTALS.CostFOBfact4.value); 
} 
Calculations
document.TOTALS.markup.value = ((((text16-text2)/text16)+((text17-text4)/text17)+ ((text18-text6)/text18)+((text19-text8)/text19)+((text20-text10)/text20)+((text21- text12)/text21)+((text22-text14)/text22)+((text23-text15)/text23))*100).toFixed(1); 
}
</script>

Related

How do I Display a link inside an if-condition using javascript based on var

im trying to change the href of my var explanation 11 based on the conditions obtained.
here's the code for the variable
if ( savings_budget_aycs > totalexp ) {
var msg="UNDER";
var explanation="You still have some excess money after factoring all your expenses in your budget. You may want to start looking at investing your excess money or increasing your savings. Do read out content on";
var explanation11=" saving and investing";
var explanation12=" to understand more.";
var explanation2="Since you have more money to use from your budget, one option is to increase your savings.";
var remaining=savings_budget_aycs-totalexp;
} else {
var msg="OVER";
var remaining=totalexp-savings_budget_aycs;
var explanation="This means that your spending has exceeded your income. You will need to make some cutbacks to be able to stay within your budget. Do read our content on";
var explanation11=" planning and budgeting";
var explanation12=" to understand more.";
var explanation2="You are over budget, so try to see what you can cut down on to save some money.";
}
and here is where i call the explanation
firstTableHtml += "<div class=\'explanation\'>"+explanation+"<a id=\'link-saving\'>"+explanation11+"</a>"+explanation12+"</div>";
Remove back slashes before the quotes.
firstTableHtml += "<div class='explanation'>"+explanation+"<a id='link-saving'>"+explanation11+"</a>"+explanation12+"</div>";

parseFloat for multiple entries with the same class

I have a category page, where I display different products. In each product I have a section displaying Was Price, Save Price and New Price. Just to illustrate the structure of the Was Price:
<p class="old-price">
<span class="price-label">Was</span>
<span class="price" id="old-price-65848">
<span class="price">
<span class="currency">£</span>
</span>
</span>
</p>
Currently on product page using jQuery I can get the was price and convert it into a number:
var oldPrice = parseFloat(jQuery('.old-price .price .price').first().text().replace(/[^0-9\.]+/g, ""), 10);
And it all works fine on product page where you have only one Was Price block. However when I go to category page I have multiple blocks using the same structure and the same class the above code picks up only the first block and ignores the rest. This can be easily shown using:
console.log(oldPrice, "%");
How can I amend the code so it will pick up all the Was Price on the category page?
Edit:
I've managed to map the old Price and the Save price using the bellow code. However I am trying to execute math function where the condition is :
var oldPrices = jQuery('.old-price .price .price').map(function(){
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
var specialPrices = jQuery('.special-price .price .price').map(function() {
return parseFloat(jQuery(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
var youSave = specialPrices / (oldPrices / 100);
Unfortunately it returns NaN value
PS: All the prices are dynamically generated.
Thanks
You can map it to get an array:
var oldPrices = jQuery('.old-price .price .price').map(function(){
return parseFloat($(this).text().replace(/[^0-9\.]+/g, ""), 10);
}).get();
console.log(oldPrices);
That's said, you'd have better to set a data-* attribute to handle old price specific to each element, e.g: <p class="old-price" data-old-price="12345">.
And btw, your snippet seems unrelevant with your posted HTML markup, there is no old price value to retrieve there except maybe regarding the ID attribute.

Calculation using jquery onkeypress

I have this type of exercise in jquery. Go here http://jsfiddle.net/LAntL/3/
For Item 1, if I add #no of quantity of Size 7, it should be multiplied by Item 1's Price displayed in text box and the result should be shown in Item 1's Ext textbox.
then if I do same for size 8.5 of Item 1, it should perform the same.
But the Ext will have (Price x Size 7 Qty) + (Price x Size 8.5 Qty)
Same will happen for Item 2. And along with this, Total quantity and Total price will be updated on keypress event of each textbox.
I'm a beginner in jquery and got this killing exercise.
Please help someone.
Thanks in advance.
I'd suggest that you assign some classes to your fields so that jQuery can easily find them:
"lineQty" - add this class to all the qty fields
"lineTotal" - add this class to all the line total fields
"linePrice" - I think you can see where I'm going with this
"lineExt" - add to all ext fields
Then the following .keyup function will do the updates on all lines automatically.
$(document).ready(function() {
$(".lineQty").keyup(function() {
// 'this' is the field the user is typing in
// so find the tr that it belongs to
var $row = $(this).closest("tr"),
total = 0,
// get the price for the current row:
price = $row.find(".linePrice").val();
// loop through every qty field for the current row and add
// the entered value to the total, using unary plus to convert
// to a number, and a default of 0 if non-numeric data is entered
$row.find(".lineQty").each(function() {
total += +this.value || 0;
});
// set the total for the current row
$row.find(".lineTotal").val(total);
// set the price for the current row
$row.find(".lineExt").val(total * price);
// now add up the grand totals
var grandTotal = 0,
grandPrice = 0;
$(".lineTotal").each(function() {
grandTotal += +this.value || 0;
});
$(".lineExt").each(function() {
grandPrice += +this.value || 0;
});
$("[name='data[totalQuantity]']").val(grandTotal);
$("[name='data[totalPrice]']").val(grandPrice);
});
});
Working demo: http://jsfiddle.net/LAntL/5/ (only works on the first line because I couldn't be bothered assigning classes to all your fields - you would need to add the classes I talk about above to every field as per what I did for the first line).
Okay, you want to learn something, so I will describe a possible way, and don't give you the finished solution.
First of all, you should mark the tables which contains items with class="item". Now you can write a selector in jQuery which gets every item separately. Then you should mark all cells (<td>) which have a special function. Total, Price, Disc and Ext. Your table should look like this:
<table class="item">
<tr>
<td>...</td>
<td class="total">...</td>
<td class="price">...</td>
<td class="disc">...</td>
<td class="ext">...</td>
</tr>
</table>
Now you can write a selector for all input fields inside of the table with class "item".
$('.item input').change(function(){});
Inside of this function you can handle the calculation. At first I would recommend to get the item:
$('.item input').change(function(){
var item = $(this).closest('table.item');
var totalInput = $(item).find('.total input');
var priceInput = $(item).price('.price input');
// ...
var allWriteableInputs = $(item).find('input[readonly!="readonly"]');
// do the calculation
var sum = 0;
$(allWriteableInputs).each(function(i, input){
sum += $(input).val();
});
$(totalInput).val(sum);
});
If you go this way, you don't need:
The onkeypress="return isNumberKey(event);" and
the id="product1Total" for every inputbox
I hope this thought-provoking impulse helps you a little bit. You have still a long way to go, my young padawan ;-)

javascript .keyup correct price formatting and more

So far I have this which is comprised of snippets. I am not an expert in JavaScript by far so if anyone could help me achieve the following I would be very grateful and hopefully learn something new today :)
I want to achieve the following:
When a user types 1000000 into the input field the results shown are as follows,
Higher than $1 million
Lower than $1 million
Between $970 thousand and $1.3 million
Currently I can achieve the correct display of digits to prices but don't know how to add the word million, thousand, hundred to the end of the prices. Plus I'm not sure how to subtract 3% and add 3% to the price for the between price part.
Here is my code so far:
<input type="text" id="price" class="liveprice" value="<?php echo $myprice; ?>" >
<p>Higher than <span id="higher"><?php echo $myprice;?></span></p>
<p>Lower than <span id="lower"><?php echo $myprice;?></span></p>
<p>In between <span id="between"><?php echo $myprice;?></span></p>
<script type="text/javascript">
// make sure it adds commas and dots to price
$.fn.digits = function() {
return this.each(function() {
$(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
})
}
// update in real time
$("input.liveprice").keyup(function() {
var value = $(this).val();
$("#higher").text(value).digits();
$("#lower").text(value).digits();
$("#between").text(value).digits();
}).keyup();
</script>
If you want to know if it is higher than 1 million, divide the number by 1 million and then round the number using Math.floor(). If the answer is higher than zero then that is "how many million" you have. You can then insert the word million using something like (you'll need to add some stuff here):
var val = $('your input').val()/1000000;
if (Math.floor(val) > 0) {
$('your element with words').text( val + " million" );
}
Do the same for 1000 but just divide by 1000 instead of 1000000.

How to efficiently use jQuery to multiply columns of dynamically rendered table

I'm working on a pretty big table/form that is dynamically created depending on stock availability. The table has 5 fields: Code, Prod.Name, Amount, Price and SubTotal. The user is supposed to set a number in the Amount field and then there's a jQuery script that multiplies that amount for the price to display the SubTotal. In the table, a product looks like this:
<tr>
<td>Princess 01</td>
<td>Conjunto corpiño y cola less <strong>Talle 85</strong></td>
<td><input type="text" id="princess-lingerie-id-963" name="[princess-lingerie][id_963]" value=""></td>
<td>$<input type="text" id="price_princess-lingerie-id-963" value="99" readonly="readonly"/></td>
<td id="subTotal_princess-lingerie-id-963" name="subTotal"></td>
</tr>
My problem is that I have many different products that belong to different product categories, so while this belongs to the "princess-lingerie" (don't laugh) category, a product from the "cosmetica" category looks like this:
<tr>
<td>D02/3</td>
<td>Magic Dual aroma Frutos Rojos</td>
<td><input type="text" id="cosmetica-stock-id-1008" name="[cosmetica-stock][id_1008]" value=""></td>
<td>$<input type="text" id="price_cosmetica-stock-id-1008" value="26" readonly="readonly"/></td>
I have actually already created the little bit of logic which would work for only one field, but I don't know how to extend it to the whole table. Could anyone give me a hand with it? ...I'm a little bit overwhelmed and don't know where to start right now.
$(document).ready(function(){
$("#princess-lingerie-id-963").keyup(function() {
var howMany = parseInt($("#princess-lingerie-id-963").val());
var subTotal = parseInt($("#price_princess-lingerie-id-963").val()) * howMany;
//assign subTotal to the td
$("#subTotal_princess-lingerie-id-963").html(subTotal);
});
});
Shad is right to suggest adding useful classes. To handle the calculations in a sustainable way across a multi-row table, you'll also need a way to generically identify which row you're calculating on. I'm sure this could be greatly improved, but here's a basic example:
The jsfiddle demo is here.
// there are two cells where the 'id' has this pattern, but only one is selectable (the other is read-only)
// still, it would be better to give it a class if at all possible to avoid confusion
// and possible tampering by users
$("input[id*=-id-]").keyup(function() {
var howMany = parseInt($(this).parent().next().find('input').val(), 10);
var subTotal = parseInt($(this).val(), 10) * howMany;
//assign subTotal to the td
$(this).parent().next().next().html(subTotal);
});
EDIT:
Updated to include radix and condition for blank value:
http://jsfiddle.net/RzBeM/2/
$("input[id*=-id-]").keyup(function() {
var howMany = parseInt($(this).parent().next().find('input').val(), 10);
var subTotal = parseInt($(this).val(), 10) * howMany;
if (isNaN(subTotal)) subTotal = 0;
//assign subTotal to the td
$(this).parent().next().next().html(subTotal);
});
First, I would start giving your inputs useful classes, like 'qty' and 'price', and then the final cell can have a class of 'subtotal'. That makes the next step possible:
jQuery('#TABLEID tr').each(function(i,E){
var subT=parseInt(jQuery(E).find('.qty').val(),10) * parseFloat(jQuery(E).find('.price').val());
jQuery(E).find('.subtotal').text('$' + subT.toFixed(2));
});
I use jQuery to iterate over each tr in the table, and run the necessary calculations.
The final solution could use a further tweaked version:
jQuery(function(){
jQuery('.qty').keyup(function(){
var E=jQuery(this).parents('tr').filter(':first');
var subT=parseInt(E.find('.qty').val(),10) * parseFloat(E.find('.price').val());
E.find('.subtotal').text('$' + subT.toFixed(2));
});
});

Categories

Resources