I have two spans one called amtTotal and another called DeepGreenTotal. I am trying to sum these two spans into the FinalTotal span you see below. I would prefer to use javascript but if jquery is utilized please make the instructions super clear as i am new to jquery, for example where i would put the script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"> because I have no idea.
<html>
<head></head>
<body>
<span class="cena-vebsajt" id="amtTotal">$0.00</span>
<span class="cena-hosting" id="DeepGreenTotal">$0.00</span>
<span class="FinalTotal">$0.00</span>
</body>
</html>
3
Answers
You’ll have to add the jQuery reference into the
<head>
tags.$(document).ready(function(){ Reference
In the vanilla JavaScript code, we use the DOMContentLoaded event to ensure that JavaScript code executes after document is loaded.
One more thing by placing the JavaScript at the end of the HTML, it provides time to load HTML first and then load the javascript; this approach improves render speed.
We get the Calculate button element using getElementById and attach a click event listener to it using addEventListener.
When the button is clicked, we retrieve the values from the spans by getting the textContent and removing the dollar sign using the replace() method.
We parse the extracted values as floats using parseFloat().
Then, we calculate the sum of the two values and store it in the sum variable. Finally, we update the textContent of the. FinalTotal span with the calculated sum, formatted as a currency value using toFixed(2).
Just get all the
<span>
elements by its identifiers, then get their content, replace the$
symbol with an empty string (we can only sum numeric values), parse the two first string type values (the addends) to float, and finally do the sum and show the result, fixed to two decimal, as part of the third<span>
content.I used template strings (“) for a more clear and clean concatenation.