parseFloat for multiple entries with the same class - javascript

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.

Related

Swap data value based on query string

We inherited some old code which is in place and working. It is a simple pricing switch between £ GBP and $ USD - the price updates onChange as seen below in the pen.
PEN link
https://codepen.io/go6/pen/rNOgaee
$(function() {
$("#curr").on("change",function() {
var curr = this.value;
var prefix = curr=="500"; // or ["usd","yen",...].indexOf(curr); for more
var sign = curr=="500"?"":"";
$(".value").each(function(){
$(this).text(
(prefix?sign:"") +
$(this).data(curr) +
(prefix?sign:"")
);
})
}).change();
});
Question
The price by default is set to USD, as per the data-usd value when the page loads. We want to supply a page URL query string eg /pricing?curr=GBP which can toggle the pricing to GBP.
Tried so far but not working
I have tried a few combinations using this Answer:
Show / Hide elements based on query string value
but so far, none have worked. Please can someone assist in implementing a query string sitch of currency?
Just add this to your code:
if(document.URL.indexOf("curr=GBP") !== -1)
{
$(".value").each(function(){
$(this).text($(this).data("gbp"));
})
$("#curr").val("gbp");
}

Using javascript to get sum from input title

Below is a javascript which is able to get the input value & needs external libraries.
I know this seem odd but I have to use javascript to grab the price from the input title and no external libraries is required. Is it possible to work from input title ?
<?php
include_once('database_conn.php');
$sqlCDs = 'SELECT CDID, CDTitle, CDYear, catDesc, CDPrice FROM nmc_cd b inner join nmc_category c on b.catID = c.catID WHERE 1 order by CDTitle';
$rsCDs = mysqli_query($conn, $sqlCDs);
while ($CD = mysqli_fetch_assoc($rsCDs)) {
//have a look at the input field below
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id="yourId" name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
}
?>
JS:
function isChecked(chosen) {
//and here it is called again
var valOfTitle = document.selectElementById("yourId").getAttribute('title');
var number = parseFloat(valOfTitle);
if(chosen.is(':checked')) {
sum = sum + parseFloat(valOfTitle);
} else {
sum = sum - parseFloat(valOfTitle);
}
$('#total').valOfTitle(sum.toFixed(2));
};
Just use getAttribute if you dont want to use any external libraries.
element.getAttribute("title")
i hope i understood you correctly:
you can access the data in your input field via jQuery's attr() method.
// "valOfTitle" is just a name..could also be "george" or "germany"
// "yourInputElementId needs to be the id of your element (written in
// "")
var valOfTitle = $(yourInputElementId).attr('title');
without jQuery:
var valOfTitle = document.selectElementById(yourInputFieldId).getAttribute('title');
if you want it as a number you can just do:
var number = parseFloat(valOfTitle);
if you don't want to add an id to your element you also can use another javascript selector, p.e. getElementsByName- but note: this will return a HTML Collection and not a single element, which means you will have to loop over this collection to access your data.
http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp
maybe this google search may help you too:
https://www.google.de/search?q=javascript+selectors&oq=javascript+selectors&aqs=chrome..69i57.4015j0j7&sourceid=chrome&es_sm=91&ie=UTF-8#q=pure+javascript+selectors
or even
How can I use the jQuery-like selector in pure JavaScript

Change color of text if value becomes > original value, Jquery

I have a div that looks like this:
<div class="Value">
<em id="ProductPrice" class="ProductPrice VariationProductPrice">$83.00</em>
</div>
I need a script that changes the color of the price value to red if it changes.
I started with this:
var original_value = $("#ProductPrice").text()
if ($("#ProductPrice").text() > original_value) {
$("#ProductPrice").css("color","red");
}
It doesn't work at all, but I don't get any errors.
Also the price value is set by a variable and can change based on what page it is on.
Any input is appreciated! Thanks!
You are comparing strings, not numbers. Convert your string to a number.
Basic idea to get the number:
var str = "$12.23";
var muNumber = parseFloat(str.replace("$",""));

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 ;-)

Calculating multiple items

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>

Categories

Resources