I have a page of items with various prices in GBP, each price is within a span with a class of price, what I would like to do is change the value of ALL the prices to that value divided by 1.2. so along the lines of
$('.price').html() / "1.2";
now i'm aware that this won't work as the format is £10,500 for example, I havent been able to find similar here but i'd like to take that £10,500 value divide it by 1.2 and have the value update to the result (£8,750). Anything I have tried thus far leaves me with NaN and i'm struggling to make progress.
Add a button for testing:
<button id="test-button">Test Currencies</button>
Add the following jQuery:
$('#test-button').on('click', function () {
// Get currency elements
var currencies = $('.price');
var newSymbol = '£';
var eRate = 0.8333;
$.each(currencies, function (index, value) {
// Change value to a number using regex
var number = Number($(this).html().replace(/[^0-9\.]+/g, ""));
// Assign new value and add number formatting
$(this).html(newSymbol + (number * eRate).toFixed(2).toLocaleString('en'));
});
});
Hope it helps.
Here you go :-)
Tested and working.
$("span").each(function()
{
var strNewString = $(this).html().replace(',','');
$(this).html(strNewString / 1.2);
});
function format_price(_input_str){
var input_str=_input_str+''; //if input integer convert to string
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if exist spaces
input_str=input_str.replace(new RegExp('£',"g"), ''); //if exist simbil £
input_str=input_str.replace(new RegExp(' ',"g"), ''); //if wxist
var input_int = parseInt(input_str)||0;
if(input_int==0){ return _input_str;} //return original string
input_str=input_int+'';
var out_str='';
while(input_str.length > 3){
out_str=input_str.substr(-3)+' '+out_str;
input_str=input_str.substr(0,input_str.length-3);
}
if(input_str.length>0){out_str=input_str+' '+out_str;}
out_str='£ '+out_str;
return out_str;
}
$('.price').each(function(){
var this_price=$(this).html();
$(this).html(format_price(this_price));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="price">12345</div>
<div class="price">76 09</div>
<div class="price">4576 09</div>
<div class="price">45</div>
<div class="price">£ 12 345 678 </div>
Related
$('#addcol-inner').click(function() {
var sum = 0;0
var collection = $('#white').find('.ui-sortable-handle');
collection.each(function(k,v){
var class_item = $(v).attr('class');
var col_class = class_item.search('');
var col_number = col_class.split('-')[2];
sum += col_number;
if(sum > 12){
return false;
}
I dont know whats is wrong, i wont sum the number of col class
this is HTML
<div id="white" class="column-container clearfix ui-sortable">
<div class="column-cell ui-sortable-handle col-md-12" data-post-content-id="3801" data-active-mode="text">
search() returns the integer index of the match, hence col_class is an integer value which has no split() method.
That line itself is redundant and can be removed as you're searching for an empty string. Also col_number will be a string, so presumably you'll need to use parseInt() to get the sum as an integer.
Update
Now that you've added your HTML, the issue is that the column number you're trying to access is the last element in the resulting array, not the second. Hence you need to amend the logic which retrieves that value. Try this:
$('#addcol-inner').click(function() {
var sum = 0; // note that the second 0 is redundant
$('#white').find('.ui-sortable-handle').each(function() {
var class_item = $(this).prop('class').split('-');
var col_number = class_item[class_item.length - 1];
sum += parseInt(col_number, 10);
if (sum > 12) {
return false;
}
})
console.log(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="white" class="column-container clearfix ui-sortable">
<div class="column-cell ui-sortable-handle col-md-12" data-post-content-id="3801" data-active-mode="text"></div>
</div>
<button id="addcol-inner">Click me</button>
I know how to grab information and assign it as a variable but I'm wondering if I can parse the information inside of a div with jquery.
For example: the div has a value of "1/3".
How do I tell jquery to take whatever is on the left side of "/" and divide that by whatever is on the right side of "1/3" to get a value of 0.3333 and with that "0.3333" assign it as a value to a variable?
You can use split on the string:
$(function() {
var text = $('#a1').text();
var splitted = text.trim().split('/')
console.log(splitted[0]);
console.log(splitted[1]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">
1/3
</div>
Or use regex:
$(function() {
var text = $('#a1').text();
var matches = text.trim().match(/(.*)\/(.*)/)
console.log(matches[1]);
console.log(matches[2]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">
1/3
</div>
EDIT
Here is a solution for some text mixed with fractions to process in decimal...
Like: <span id="fraction">My portion is 1/3 ok? So there is 2/3 left for you.</span>
And rebuild the original string as a result like:
<span id="decimal">My portion is 33% ok? So there is 67% left for you.</span>
I've had a super fun time!
;)
See comments in code.
CodePen
// Our input string.
var fractionText = $("#fraction").html();
var number;
var divider;
var calculatedArr=[];
var text=[];
var showRes="";
// Parse the string for fraction and text based on a regular expression.
let fractionParts;
var pattern = /([\D.]+)?(\d)+(\/)(\d)+([\D.]+)?/g;
while ((fractionParts = pattern.exec(fractionText)) !== null) {
if (fractionParts.index === pattern.lastIndex) {
pattern.lastIndex++;
}
fractionParts.forEach((match, groupIndex) => {
// If there is a match, text is optional in the regex.
if(typeof(match)!="undefined"){
switch (groupIndex){
case 0:
// Nothing to do, that is the full match.
break;
case 1:
if(typeof(match)!="undefined"){
text.push(match);
}
break;
case 2:
number = parseInt(match);
break;
case 3:
// Nothing to do, that is the / (division sign).
break;
case 4:
divider = parseInt(match);
calculated = number/divider;
if(!isNaN(calculated)){
calculatedArr.push(calculated.toFixed(2));
}
break;
case 5:
text.push(match);
break;
default:
// Nothing to do.
break;
}
}
});
}
// Determine wich one is the longuest array
// (text or calculated number) before building the result string.
var LongestArr;
if(calculatedArr>text){
LongestArr=LongestArr;
}else{
LongestArr=text;
}
// Build the string.
for(i=0;i<LongestArr.length;i++){
if(typeof(text[i])!="undefined"){
showRes += text[i].toString();
}
if(typeof(calculatedArr[i])!="undefined"){
showRes += calculatedArr[i]*100 + "%";
}
}
// Show result in page.
$("#decimal").html(showRes);
span{
padding:4px;
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fraction: <span id="fraction">My portion is 1/3 ok? So there is 2/3 left for you.</span><br>
<br>
Decimal: <span id="decimal"></span>
First answer
This works fine if you have only a fraction...
But if you have other text in front of the fraction, it will fail.
var divText = $("#test").html();
var divTextArr = divText.split("/");
var number = divTextArr[0].trim();
var divider = divTextArr[1].trim();
var calculated = parseInt(number)/parseInt(divider);
$("#result").html(calculated);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fraction: <span id="test">1/3</span>
<br>
Calculated: <span id="result"></span>
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
I am trying to get prices from between span tags. I would like to have all prices in an array. I cant seem to get it to work, I am guessing my regex is incorrect.
I am looking for any span tags with the class 'amount', the tag has no other attributes set and only has one class. E.g. <span class="amount">£9.99</span>
var prices = resp.fragments['data'].match(/<span class=\"amount\">(.*?)<\/span>/g)
.map(function(val){
return val;
});
Output
[ '£9.99', '£100.00' ]
* UPDATE *
Turns out it was an encoding with the ajax response resp.fragments['data'].
I was using regex as it is something I have not really used before in JS and thought I would have a play. I did look at many examples and after about 45 mins with no success I thought a fresh set of eyes would fix it.
#spaceman
Thanks for the helpful comment. Your one of those people if someone asked "Is there is a doctor in the house?", you would stand up and say "Sweet load there are loads of doctors out there".
While a regular expression could work for this, it might be easier to simply select the <span class='amount'> elements and map their innerHTML content to an array via the map() function:
// This would yield an array containing your values
var amounts = Array.prototype.slice
.call(document.querySelectorAll('span.amount'))
.map(function(a){ return a.innerHTML; });
You can see a working example of this demonstrated here.
Simplest method will be to add this to an invisible DOM object and then traverse it via DOM API
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
//now append it to an DOM object
var wrapperDiv = "<div style='display:none' id='tmpDiv'>" + text + "</div>";
document.body.innerHTML += wrapperDiv;
var elements = document.querySelectorAll( "#tmpDiv amount" );
var output = Array.prototype.slice.call( elements ).map( function(val){
return val.innerText;
})
Another approach could be split the text by <span class="amount"> and get the value after first index
DEMO
var text = '<span class="amount">£9.99</span><span class="amount">£9.99</span>'
var output = [];
text.split('<span class="amount">').forEach( function(val, index) {
if (index > 0 )
{
output.push( val.replace( "</span>", "" ) );
}
});
document.body.innerHTML += JSON.stringify( output, 0, 4 );
You can use this instead.
var prices = document.getElementsByClassName('amount');
var price_array = [];
for (i= 0; i < prices.length; ++i) {
price_array.push(prices[i].innerHTML);
}
document.write(" | " + price_array);
<span class='amount'>£123</span>
<span class='amount'>£3</span>
<span class='amount'>£5</span>
<span class='amount'>£64</span>
You don't need to use regex or jQuery for this.
what i aim to do is a very simple currency converter. Basically, you type in a number, and press a button, a text is displayed that says "x dollars is y euros". Press the button again, a new text is displayed where the old one was, and the old one is displayed under the new one.
I've come so far that when something is entered in the field, it pops up below, and if you press the button again (with the same or a different value) it becomes a list of text.
To clarify what it is i'm saying here, take a look at this jsfiddle: http://jsfiddle.net/w8KAS/5/
Now i want to make it so that only numbers work, and so that number(x) is converted when the button is pressed and displayed below next to some fitting text (like "x dollars is y euros")
This is my js code, check the jsfiddle full code (html, js, css)
Any suggestions?
var count = 0;
function validate() {
var amount = document.querySelector("#amount");
if(amount.value.length > 0) {
amount.className = 'correct';
}
else {
amount.className = 'empty';
}
if (document.querySelector('.empty')) {
alert('Något är fel');
}
else {
addconvert(amount.value);
}
}
function addconvert(amount) {
var table = document.querySelector('#tbody');
var tr = document.createElement('tr');
var amountTd = document.createElement('td');
var amountTextNode = document.createTextNode(amount);
amountTd.appendChild(amountTextNode)
tr.appendChild(amountTd);
table.insertBefore(tr, table.firstChild);
count++;
}
var button = document.querySelector(".button");
button.onclick = validate;
Your number validation is failing. Change the first part of your validation to this:
function validate() {
var amount = document.querySelector("#amount");
var amountNum = parseFloat(amount.value); //This is the numeric value, use it for calculations
if(amount.value.length > 0 && !isNaN(amountNum) ) {
amount.className = 'correct';
amount.value = amountNum;
}
...
Working here: http://jsfiddle.net/edgarinvillegas/w8KAS/6/
Cheers
You need a conversion rate (there are APIs for that), and then you can just add them together in a string
var convRate = 1.3;
var amountTextNode = document.createTextNode(amount + " dollars is " + amount*convRate + " euros");
Regarding the API, Yahoo will tell you what you need without even the need to sign-in
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
}).done(function(data) {
convRate = data.query.results.rate.Rate
});
To make sure that only numbers work, you can test the variable amount.value using the isNaN function. This will return true if the user's input is Not-a-Number, so if it returns false, you can proceed with your conversion.
if (!isNaN(amount.value)){
addconvert(+amount.value) // the plus symbol converts to a number
} else {
// display error here
}
Inside your addconvert function, you can add code to will multiply your input amount by an exchange rate to get a rough conversion.
function addconvert(){
// ...
var euros = 0.74 * amount
var text = amount + ' dollars is ' + euros + ' euros'
var amountTextNode = document.createTextNode(text);
What i'm trying to do is taking the price of every input checked, making a sum out of it.
Here's my code
function totalSum(e) {
e.preventDefault();
var unit = $("input:checked").parent("dt").siblings("dd").find("span");
total = 0;
$.each(unit, function(index, obj){
total += parseInt($(obj).text(), 10);
});
$("#totalPrice").html('<span class="count">€ ' + total + '</span> €');
}
Every unit is found inside its span. Total is set to 0. I try to call a parseInt on each checked object, then add the total inside a span. In HTML, price is stated like that:
<dd><span class="costo">€199</span></dd>
So as you see there is the Euro mark. I am afraid it could not be parsed, is this it? Because nothing change! How should I write it?
Thanks in advance
Ok I feel so ashamed but I cannot get it to work. I decided to put the code at its minimum, so I tried that way
<body>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div class="bla"><span class="count">1</span></div>
<div id="total"></div>
<script type="text/javascript" src="js/jquery-1.9.0.min.js" /></script>
<script>
$(document).ready(function(){
function sum() {
var prices = $("div.bla").find(".count");
total= 0;
$.each(prices, function(index, obj){
total += parseFloat($(obj).text());
});
$("#total").html('<span class="count">'+total +'</span> €');
};
});
This should work, yet nothing appear. Could someone be so kind to tell me what's going wrong?!
You can just replace any non-numeric characters:
total += parseInt($(obj).text().replace(/[^\d.-]/, ''), 10);
Also, you can do unit.each() instead of $.each(unit, but that has no effect on what you're trying to do.
You can simply remove the unit from the text :
var text = $(obj).text().replace(/[€\$]/,''); // add other units if needed
total += parseInt(text, 10); // are you sure you don't prefer parseFloat ?
Or, if you want to only keep digits and + and -, do
var text = $(obj).text().replace(/[^\d\-\+]/g, '');
Change your parseInt to skip the first character.
total += parseInt($(obj).text().substring(1),10);
After a couple of days trying and reading the best way to do it, I believe this could be an elegant solution of what I was trying to achieve :)
$("input").on("click", function() {
var j = $("input:checked");
t = 0;
$(j).each(function() {
t += parseInt(this.value, 10);
});
$("#total").html("<span>€ " + t + "</span>");
});