I'm trying to create a script that get some values from several selectboxes and then do some math with them.
The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.
The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.
I've created a fiddle here I think that describes my problem best!
My script
function update_amounts() {
var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
var korting = ((100-perc)/100);
var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
var adviesprijsValue = parseFloat(adviesprijs) || 0;
var sum = 0.0;
$('#product_configure_form .product-configure-custom-option select').each(function () {
var optionText = $(this).find('option:selected').text();
var matches = optionText.match(/\(([^)]+)\)/g) || [];
if (matches.length > 0) {
var priceText = matches[matches.length - 1];
if (priceText.indexOf("€") > -1) {
var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
var priceValue = parseFloat(priceClean) || 0;
sum += priceValue;
}
}
});
var sum2 = sum+adviesprijsValue;
var sumBtw = (sum2*1.21).toFixed(2);
$('#amount').text('€' +sum2);//
$('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
}
$(document).ready(function(){
$( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
});
The HTML is pretty long so best is to take a look at the Fiddle.
Can anybody help me to make a correct calculation...?!
Thx in advance
Your conversion from Dutch formatting to normal float formatting is incorrect.
Consider using:
.replace(/[^\d,]/g,"").replace(",",".")
Working example: http://jsfiddle.net/pgaphma3/3/
EDIT
To allow also a plus or minus sign use /[^\d,\-+]/g
Related
I am working on a script to calculate some stuff using multiple input. I have been copy-pasting my script because it has been working for 2 values calculations. For example:
//Diameter Pitch
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.dpModule').val());
var valZ = parseInt($('.dpJumlahGigi').val());
var sum = valZ*valM;
$("input#resultDP").val(sum);
});
});
But now I am trying to add another variable Phi (3.14) but the calculation is not working
//Circular Pitch
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valD = parseInt($('.cpPitchDiameter').val());
var valT = parseInt($('.cpAot').val());
var phi = parseInt($('3.14').val());
var sum = phi*valD/valT;
$("input#resultCP").val(sum);
});
});
The circular pitch script resulted with NaN, can anyone please fix my code? I am trying to make the following formula:
var sum = 3.14*valD/valT;
Much thanks in advance
Replace: var phi = parseInt($('3.14').val()); with var phi = 3.14;.
Your current code is trying to look for a '3.14'tag in your HTML so it returns "not a number" since that doesn't exist in the HTML.
Having some trouble getting this right. I'm very new to jQuery, so trying to get better and learn.
Currently I am getting 2 different values from a html table using the following code
var sellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var buyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
These both output a value such as $13,000,000
I am then wanting to subtract 1 from these values (making it $12,999,999) before pasting them to an input as such
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
However, I am having some trouble with how to subtract $1 from these.
I tried using sellPrice--; but without success.
I've also tried adding - 1; at the end of each variable, but did not succeed either.
I tried to test something like this, but did not work either.
var minusOne = -1;
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = (getCurrentSellPrice - minusOne);
var buyPrice = (getCurrentBuyPrice - minusOne);
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);`
Trying my best to familiarize myself with jQuery :)
Any help is much appreciated!
Solved using this
var getCurrentSellPrice = $('.qt').find("tr:eq(2)").find("td:eq(4)").html();
var getCurrentBuyPrice = $('.break .main-col .qt').find("tr:eq(2)").find("td:eq(4)").html();
var sellPrice = Number(getCurrentSellPrice.replace(/[^0-9\.]+/g,"")) - 1;
var buyPrice = Number(getCurrentBuyPrice.replace(/[^0-9\.]+/g,"")) + 1;
$('input[name="sell"]').val(sellPrice);
$('input[name="buy"]').val(buyPrice);
Since your numbers contain currency symbol and are strings, you need to convert them to proper numbers before subtracting them. See the answer below.
How to convert a currency string to a double with jQuery or Javascript?
I have an online store that has limited access to make any correct edits to code.
I am trying to implement proper Price Schema as they have:
<span itemprop="price">$57.00</span>
This is incorrect.
It needs to be set up like this
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price">57.00</span>
Is there something in JavaScript or jQuery that can manipulate this by separating the Currency Symbol and Price?
Thanks
You get the ELEMENT text:
var value = $("span[itemprop='price'").text();
Then you could generate the html using regex like:
var html = '$57.00'.replace(/([^\d])(\d+)/,
function(all, group1, group2){
return 'some html here =' + group1 + '= more hear =' + group2 });
Might not be 100% bug-free, but it should get you started:
<script type="text/javascript">
var n = document.getElementsByTagName('*')
for(var i=0;i<n.length;i++)
{
if(n[i].hasAttribute('itemprop')) //get elements with itemprop attribute
{
var p = n[i].parentNode
var ih = n[i].innerHTML //grab the innerHTML
var num = parseFloat(ih) //get numeric part of the innerHTML - effectively strips out the $-sign
n[i].innerHTML = num
//create new span & insert it before the old one
var new_span = document.createElement('span')
new_span.innerHTML = '$'
new_span.setAttribute('itemprop', 'priceCurrency')
new_span.setAttribute('currency', 'USD')
p.insertBefore(new_span, n[i])
}
}
</script>
Somthing along the lines of
// find all span's with itemprop price
document.querySelectorAll("span[itemprop='price']").forEach(function(sp){
// grab currency (first char)
var currency = sp.innerText.substr(0,1);
// remove first char from price val
sp.innerText = sp.innerText.substr(1);
// create new element (our price-currency span)
var currencySpan = document.createElement("span");
currencySpan.innerText = currency;
currencySpan.setAttribute("itemprop", "priceCurrency");
currencySpan.setAttribute("content", "USD");
// Append it before the old price span
sp.parentNode.insertBefore(currencySpan, sp);
});
Should do what your after.
See demo at: https://jsfiddle.net/dfufq40p/1/ (updated to make effect more obvious)
This should work -- querySelectorAll should be a bit faster, and the regex will work with more than just USD, I believe.
function fixItemPropSpan() {
var n = document.querySelectorAll('[itemprop]');
for (var i = 0; i < n.length; i++) {
var p = n[i].parentNode;
var ih = n[i].innerHTML;
var num = Number(ih.replace(/[^0-9\.]+/g, ""));
n[i].innerHTML = num;
//create new span & insert it before the old one
var new_span = document.createElement('span');
new_span.innerHTML = '$';
new_span.setAttribute('itemprop', 'priceCurrency');
new_span.setAttribute('currency', 'USD');
p.insertBefore(new_span, n[i]);
}
}
Here is a suggestion of how you can make this work, though i would not suggest doing it like this (too many cases for content="").
Example of the logic you could use to transform the incorrect format to the correct one.
Hope you find it useful. :]
I am currently building a filter based on div class's and contents.
I was wondering if it is possible to pass a string like follows into a function:
"£0.01 - £100.01"
and then have the function show all div's where the html of that div is between this range
so say I have a div with a class of "price" and its contents were: £10.30
from running this function and passing the string of "£0.01 - £100.01" into it it would hide all div's similar to how I have done it in the js below then only show the div's where the div class "price"'s contents were within the selected price range.
I have managed to do something similar with a brand filter which I will provide here:
function brand(string){
var brand = string;
$('.section-link').hide();
$('.section-link').children('.brand.' + brand).parent().show();
if (brand == "All Brands"){
$('.section-link').show();
}
}
Any general advice or code is greatly appreciated to help achieve this :)
Thanks,
Simon
Edit:
Target div example:
<div class="section-link">
<div class="price"> £56.99</div>
</div>
Reply's are helping a lot, the filter function looks awesome so thanks for pointing that out.
I am just trying to find a way to split the initial string being past in, into two values one low and one high as well as stripping the £ signs
Edit:
managed to split the original string:
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
alert(rangearray[0]);
alert(rangearray[1]);
FINAL EDIT:
From the reply's I have kind of been able to make a function, however it is not entirely working :) can anyone spot what I have done wrong?
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0];
high = rangearray[1];
$('.section-link').children('.price').each(function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
if (low <= divprice && high >= divprice){
$(this).parent().show();
}
})
}
Okay its working, I had spaces in my string. The final function (although messy :P) is:
function price(string){
$('.section-link').hide();
var range = string.replace(/\u00A3/g, '');
var rangearray = range.split("-");
low = rangearray[0].toString();
high = rangearray[1].toString();
lowmain = low.replace(/ /g,'');
highmain = high.replace(/ /g,'');
$('.section-link').children('.price').each(
function() {
var divprice = $(this).text().replace(/\u00A3/g, '');
var maindivprice = divprice.replace(/ /g,'');
if (lowmain <= maindivprice && highmain >= divprice){
$(this).parent().show();
}
})
}
I'd use a function like this one, where range is the string you gave
function highlightDivs(range) {
var lower = range.split(" ")[0].slice(1);
var upper = range.split(" ")[2].slice(1);
$('.section-link').hide();
$('.section-link').children('.price').each(function() {
if (lower <= $(this).val() && upper >= $(this).val()){
$(this).parent().show();
}
});
}
You can use jQuery's build in filter() function, and write a filter with the condition you described.
First, you should hide all the items with any price.
$(".price").parent().hide();
Then, you can filter all the items with in-range prices and show them:
$(".price").filter(function(){
var $this = $(this);
var value = $this.val();
return (value >= minNumber && value <= maxNumber); // returns boolean - true will keep this item in the filtered collection
}).parent().show();
Use jQuery's filter()
An example -> http://jsfiddle.net/H6mtY/1/
var minValue = 0.01,
maxValue = 100.01;
var filterFn = function(i){
var $this = $(this);
if($this.hasClass('amount')){
// assume that text is always a symbol with a number
var value = +$this.text().match(/\d+.?\d*/)[0];
if(value > minValue && value < maxValue){
return true;
}
}
return false;
};
// apply your filter to body for example
$('#target span')
.filter(filterFn)
.each(function(i,ele){
// do something with the selected ones
$(this).css('color','red');
});
I would go by something like:
Get all the divs that have prices.
Iterate through all:
Transform the strings (minus the pound symbol) to float numbers and compare with an IF statement if they are inside the provided range.
If they are just go to the next (use continue maybe)
Else (not in the range) add a class like .hide so it can be blended through css (or just use the blend function from jquery)
My current solution does not calculate the added ship cost. My condition isn't working, I've been able to do similar problems with functions but I would like to know where I went wrong here.
<html>
<script type="text/javascript">
var numOrdered = 0;
var priceItem = 0;
var shipCost = 0;
var amtDue = 0;
numOrdered = prompt("Enter the number ordered ",0);
priceItem = prompt("Enter the price of the item ",0);
amtDue = numOrdered * priceItem;
if (amtDue > 1000)
{
shipCost = 0;
}
else
{
shipCost = amtDue * .1;
}
amtDue = amtDue + shipCost;
document.write("You owe ", amtDue);
</script>
</html>
It works for me. I put your code here: http://jsfiddle.net/XVzKb/
No changes -- if I enter 5 and then when prompted again 10 the total displayed in the page is 55 which is 5 * 10 * 1.1 = 55. Note that if your input includes a non-numeric character like $ or , then you'll need to parse it like so:
number = parseInt(response.replace(/[^0-9]/g, ''), 10)
I would check out the developer tools in Chrome or Firefox and use console.log or put in some break points to help you understand what is working and what is not. This way you can see if its your javascript or your html document that is failing.
That being said, you are comparing strings not numbers, so you'll want to use parseInt on the values you are getting back from the prompt.
priceItem = parseInt(priceItem, 10);