Bishan
Bishan

Reputation: 15702

Get the value using class name in jquery

I'm trying to get the value of an input text field and multiply it by quantity and display on total column.

Here is the jsfiddle

Html

Price: <input id="price" type="text"/>
<table id="my-table">
<tr>
   <td>Quantity</td>
   <td>Total</td>
</tr>   
<tr>
    <td class="quantity">15,447.84</td>
    <td class="total"></td>
</tr>
<tr>
    <td class="quantity">89.28</td>
    <td class="total"></td>
</tr>
</table>

Script

$(document).ready(function () {
    $('#price').on('change', calTotal);
    function calTotal() {
        var p = $('#price').val();
        var q = $('.quantity').text();
        alert(q);
    }
});

var q = $('.quantity').text(); give me output as 15,447.8489.28.

How can I multiply each quantity by price and print on total column?

Upvotes: 3

Views: 1584

Answers (1)

Shaunak D
Shaunak D

Reputation: 20626

  • Use parseFloat() and .text() to set the values.

  • Also you have two columns for total and quantity each, you need to check values of both the respective columns while assigning the text in total

  • You need to convert 15,000 to 15000, use replace() for this.


$('.total').text(function(){
    var q = $(this).prev().text();
    q = q.replace(/,/g, '');                
    p = p.replace(/,/g, '');  
    return (parseFloat(p)*parseFloat(q))
});

Fiddle Demo

Upvotes: 6

Related Questions