skip to Main Content

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


  1. $(document).ready(function(){
      $("#btnCalculate").click(function(){
        var val1 = parseFloat($('#amtTotal').text().replace(/[$,]+/g,""));
        var val2 = parseFloat($('#DeepGreenTotal').text().replace(/[$,]+/g,""));
        var total = val1 + val2;
        $('span.FinalTotal').text('$' + total);
      });
    });
    <html>
      <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
      <body>
           <span class="cena-vebsajt" id="amtTotal">$10.05</span>
           +
           <span class="cena-hosting" id="DeepGreenTotal">$5.08</span>
           =
           <span class="FinalTotal">$0.00</span>
    
    <div>
      <button type="button" id="btnCalculate">Calculate</button>
    </div>
    </body>
    </html>
    • You’ll have to add the jQuery reference into the <head> tags.

    • $(document).ready(function(){ Reference

    The ready() method is used to make a function available after the
    document is loaded. Whatever code you write inside the $(document
    ).ready() method will run once the page DOM is ready to execute
    JavaScript code.

    • $("#btnCalculate").click(function(){ Reference

    Bind an event handler to the "click" event, or trigger that event on
    an element.

    Returns the text content of the selected elements.

    • $(‘#amtTotal’).text().replace(/[$,]+/g,"") Reference

    Replaces commas ‘,’ with an empty string to avoid errors using Regex.

    Parses a value as a string and returns the number as a float value.
    Then we can perform calculations.

    • $(‘span.FinalTotal’).text(‘$’ + total); Reference

    Writes the total into the span text.

    Login or Signup to reply.
  2. <html>
      <head>
    
      </head>
      <body>
           <span class="cena-vebsajt" id="amtTotal">$10.05</span>
           +
           <span class="cena-hosting" id="DeepGreenTotal">$5.08</span>
           =
           <span class="FinalTotal">$0.00</span>
    
    <div>
      <button type="button" id="btnCalculate">Calculate</button>
    </div>
    <script>
    // Get element by ID
    const getElById = (id) =>  document.getElementById(id);
    
    // Get values from span
    const getValuesFromSpan = (id) => parseFloat(getElById(id).textContent.replace('$', ''));
    
    // Wait for the document to load
    document.addEventListener('DOMContentLoaded', function() {
      // Get the Calculate button element
      var btnCalculate = getElById('btnCalculate');
      
      // Attach click event handler to the Calculate button
      btnCalculate.addEventListener('click', function() {
        // Get the values from the spans
        var amtTotal = getValuesFromSpan('amtTotal');
        var DeepGreenTotal = getValuesFromSpan('DeepGreenTotal');
        
        // Calculate the sum
        var sum = amtTotal + DeepGreenTotal;
        
        // Display the sum in the FinalTotal span
        document.querySelector('.FinalTotal').textContent = '$' + sum.toFixed(2);
      });
    });
    </script>
    </body>
    </html>
    

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

    Login or Signup to reply.
  3. 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.

    const 
        a = parseFloat(document.querySelector("#amtTotal").textContent.replace("$", "")),
        b = parseFloat(document.querySelector("#DeepGreenTotal").textContent.replace("$", "")),
        c = document.querySelector(".FinalTotal");
    
    c.textContent = `$${(a + b).toFixed(2)}`;
    <span class="cena-vebsajt" id="amtTotal">$20.80</span> + 
    <span class="cena-hosting" id="DeepGreenTotal">$71.50</span> = 
    <span class="FinalTotal">$0.00</span>

    I used template strings (“) for a more clear and clean concatenation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search