Read the content of a child of a child with javascript - javascript

i'd like to create a function that gets prices as dynamic content and calculates an installment payment. I tried several approaches but they do not work. Unfortunately i don't get an error msg.
Maybe you could help my drenched brain a bit. Thank you a lot in advance
var wrapper = document.getElementsByClassName('article-price')[0];
var secondwrapper = wrapper.getElementsByTagName('span')[0];
var price = secondwrapper.getElementsByTagName('span')[0];
var installment = document.getElementById('installment');
installment.innerHTML = (price.innerHTML / 12).toFixed(2);
<span class="article-price">
<span>
<span>149,99</span>
<span>€</span>
</span>
</span>
<div>your installment is <span id="installment"></span></div>

Replace var price = secondwrapper.getElementsByTagName('span')[0]; by var price = parseFloat(secondwrapper.getElementsByTagName('span')[0].innerHTML.replace(',','.')); to get the content of your span and replace comma by point to get the string as float number.
If you don't replace replace the comma by a point, JavaScript won't understand that '149,99' is a number and will only keep '149' because , is not recognized as decimal separator, while . is.
getElementsByTagName will give you the whole tag and not only the value inside as you wanted. Then in last line, remove price.innerHTML to price because you already converted it earlier.
Here's a snippet to help you
var wrapper = document.getElementsByClassName('article-price')[0];
var secondwrapper = wrapper.getElementsByTagName('span')[0];
var price = parseFloat(secondwrapper.getElementsByTagName('span')[0].innerHTML.replace(',','.'));
var installment = document.getElementById('installment');
installment.innerHTML = parseFloat(price / 12).toFixed(2) + " €";
<span class="article-price">
<span>
<span>149,99</span>
<span>€</span>
</span>
</span>
<div>your installment is <span id="installment"></span></div>
I hope my answer helped you !

var wrapper = document.getElementsByClassName('article-price')[0];
var secondwrapper = wrapper.getElementsByTagName('span')[0];
var price = secondwrapper.getElementsByTagName('span')[0];
var installment = document.getElementById('installment');
installment.innerHTML = (parseFloat(price.innerHTML) / 12).toFixed(2);
<span class="article-price">
<span>
<span>149,99</span>
<span>€</span>
</span>
</span>
<div>your installment is <span id="installment"></span></div>
Could it be the comma inside the span throwing things out. Not sure if it will work but you could try parseFloat, which should read it as a number or parseInt;

You need to change last line of code only:
installment.innerHTML = (parseFloat(price.innerHTML.replace(/\,/g,"")) / 12).toFixed(2);

Please check the below code it might help
$(document).ready(function(){
var wrapper = document.getElementsByClassName('article-price');
alert(wrapper);
var secondwrapper = wrapper[0].getElementsByTagName('span')[0];
alert(secondwrapper.innerHTML);
var price = secondwrapper.getElementsByTagName('span')[0];
alert(price.innerHTML);
var installment = document.getElementById('installment');
installment.innerHTML = (parseFloat(price.innerHTML) / 12).toFixed(2);
});
instead of wrapper you have to use wrapper[0] which will point to zeroth position of the span and moreover you have to change the text to float
installment.innerHTML = (parseFloat(price.innerHTML) / 12).toFixed(2);

Related

Javascript to strip html and currency symbol

I have this html:
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>
I want to extract just the value of '49.99' without the html and currency symbol.
I have tried this:
function() {
var element = document.querySelector('.price-amount');
var price = element.innerHTML.replace('£', '');
return price;
}
But the result is this:
<span class="price-currencySymbol">£</span>49.99
Rather than: 49.99
Try this
var price = element.innerHTML.match(/\d+\.\d+/)[0];
where
.match searches the pattern of price using regex.
[0] returns the first match, and in your case it would be the only match.
If you want to delete what's in the '.price-currencySymbol' span in every case, you juste have to empty its html:
document.querySelector(".price-amount").innerHTML = "";
By using selector logic and accessing the proper text node you don't even need to use regexp.
var price = document.querySelector(".price-amount")
.childNodes[1].textContent;
console.log(`Extracted price: ${price}`);
<span class="price-amount amount"><span class="price-currencySymbol">£</span>49.99</span>

How to multiply span inner by id using JavaScript?

I have a span which shows a currency.
This is my span:
<span id="v3_40"></span>
It will only show the currency when it's being loaded through a browser and it needs the script bellow to show the result:
<script src="//service.arzlive.com/p.js"></script>
It shows a currency number like this: 38,355
How can i extract this number out from this span and multiply it by another number and show it as the result in another span?
I need a code to get the numeric value out from the span
You can use innerHTML to get and set your span values.
document.getElementById('new').innerHTML = document.getElementById('v3_40').innerHTML * 12;
<span id="v3_40">38.355</span>
* 12 =
<span id="new"></span>
EDIT:
After seeing the comments to this answer, here's a more detailed approach;
var originalPrice = document.getElementById('v3_40').innerHTML;
var price = originalPrice.replace(/\,/g,'');
var newPrice = parseFloat(price,20) * 12;
newPrice = newPrice.toLocaleString();
document.getElementById('new').textContent = newPrice;
Hope that helps!

Why am I receiving a NaN on parsing an number in Javascript

I can't find why I'm receiving a NaN for printing a number out with javascript.
The following code I use is repeated elsewhere on the website and works fine.
The URL in question is: http://all-american-gold10.mybigcommerce.com/us-silver-eagles/
My code is as follows:
function setCheckPrice() {
$('.NormalPrice').each(function(key, val) {
var price = $(val).html().replace('$', '').replace(',', '');
var newPrice = parseInt(price) * .03;
var setPrice = Math.floor(price - newPrice);
var credit = '<small style="font-size: 20px !important;"> - credit card price</small>';
var check = '<p><em class="new-price">$' + setPrice +'<small style="font-size: 20px !important;"> - check price</small></em></p>';
$(val).append(credit);
$(val).prepend(check);
})
};
setCheckPrice();
My code takes a number found by a specific class name, does some math and spits in back out with some extra html to go along with it. I've tried to switch the ways I've outputted the code with append, prepend, before & after, but none seem to work? Any reason why this is acting so strange?
The price variable has additional html in it. You should consider having separate elements with a class that contains just the value that you need, and nothing else. As a quick fix, this change:
var price = $(val).val().replace('$', '').replace(',', '').replace(" ","");
get's me a value of 490 for price on that page, which is what you're looking for.

Add values together using jquery

I have 3 span tags that hold the price for each item and shipping. I need to add the three span tags together to come up with the total price using jQuery. Here is my code:
<div id="relative">
<div id="absolute">
Widget 1: <span id="widget_1_price">$99.99</span><br />
Widget 2: <span id="widget_2_price">$14.99</span><br />
Shipping Fee: <span id="shipping_price">$10.00</span><br />
<b>Total: <span id="total_price"></span></b>
</div>
</div>
I have tried several methods but none seem to work for me.
Loop through the elements and parse the text in them, and add them together:
var sum = 0;
$('#widget_1_price,#widget_2_price,#shipping_price').each(function(){
sum += parseFloat($(this).text().substr(1));
});
$('#total_price').text('$' + Math.round(sum * 100) / 100);
Demo: http://jsfiddle.net/QTMsE/
var val1 = parseFloat($("#widget_1_price").text().substring(1));
var val2 = parseFloat($("#widget_2_price").text().substring(1));
var shipping = parseFloat($("#shipping_price").text().substring(1));
var all = val1 + val2 + shipping;
$("#total_price").text("$"+all);
Try this.
Try this:
total = parseFloat($('#widget_1_price').text().slice(1))+
parseFloat($('#widget_2_price').text().slice(1))+
parseFloat($('#shipping_price').text().slice(1));
$('#total_price').text('$'+total);

Overwriting <div id> with a variable in javascript

Im developing a prototype mobile web app that mimics a shopping cart. Ive been able to create the shopping cart and add products to the cart. The trouble im having is overwriting the total cost value. Im able to convert the values in order to perform the calculation but im unable to overwrite the value where the total value is stored. Here is the code ive got to far:
<div data-role="content">
<div class="ui-grid-b">
<div class="ui-block-a">Title</div>
<div class="ui-block-b">Format</div>
<div class="ui-block-c">Price</div>
<div class="ui-block-a"><p id = "myTitle"></p></div>
<div class="ui-block-b"><p id = "myFormat"></p></div>
<div class="ui-block-c"><p id = "myPrice"></p></div>
<div class="ui-block-a"></div>
<div class="ui-block-b"></div>
<div class="ui-block-c"><p id="myTotal"></p></div>
</div>
</div>
Now i wish to update the value stored in the "myTotal" id. I have a function called addtocart() and here is the code for that:
`
var total = 0;
function addtocart() {
var title = game.Title ;
var price = game.Price ;
var format = game.Format ;
var newParagraph = document.createElement('p');
newParagraph.textContent = title;
var newParagraph2 = document.createElement('p');
newParagraph2.textContent = format;
var newParagraph3 = document.createElement('p');
newParagraph3.textContent = price;
document.getElementById("myTitle").appendChild(newParagraph);
document.getElementById("myFormat").appendChild(newParagraph2);
document.getElementById("myPrice").appendChild(newParagraph3);
price = parseInt(price, 10);
price = total + price;
var newParagraph4 = document.createElement('p');
newParagraph4.textContent = total;
document.getElementById("myTotal").appendChild(newParagraph4);
}
`
Now i know the appendChild is for adding text to a document but I can seem to find a solution to overwrite the value with the new value stored in 'total' when a new item is added.
Thanks in advance :)
Use the innerHTML property. This will set the HTML inside the element to whatever you set, rather than adding a node.
var newParagraph4 = "<p>" + total + "</p>";
document.getElementById("myTotal").innerHTML = newParagraph4;
This performs less DOM manipulations and is faster than creating the paragraph on the DOM and then adding it.
Change .textContent to innerHTML:
var newParagraph4 = document.createElement('p');
newParagraph4.innerHTML = total;

Categories