Search code examples
javascriptjqueryhtmlmultiplication

Multiply 2 HTML classes and output total using jQuery


I'd like to multiply the content of 2 below fields and output the total in another div (24 * £20.00):

<label class="tm-show-picker-value" for="tmcp_range_4">24</label>
<span class="price amount final">£20.00</span>

I have tried the below method using jQuery but i'm not greatly familiar with this - https://jsfiddle.net/e8shpr0e/

$('.total').html(
  parseFloat($('.tm-show-picker-value').text()) * parseFloat($('.price amount final').text())
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label class="tm-show-picker-value" for="tmcp_range_4">24</label>
<span class="price amount final">£20.00</span>
<div class="total"></div>

Any help would be great.


Solution

  • There are 2 problems in your code.

    1. you should not use space in your classnames.
    2. your "dollar" sign is resulting in error parsing your float.

    use the following code.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <label class="tm-show-picker-value" for="tmcp_range_4">24</label>
    <span class="price_amount_final">£20.00</span>
    <div class="total"></div>
    
    
    
    var quantity = parseFloat($('.tm-show-picker-value').text());
    var cost = parseFloat($('.price_amount_final').text().replace("£", ""));
    $('.total').text("£" + quantity * cost );