I have a datatable and there is a 'amount' column. I have a js function to seperate thousand and add currency mark to each amount in the table. However the function is not working on "each" row but only works on first row. When I google it, I understand that I need to add this function in a jquery each function. Could you help me about how to make this happen?
function numberWithCommas(x) {
return "₺" x.toFixed(2).toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
}
var val = parseInt($('#tutar').text());
//Use the code in the answer above to replace the commas.
val = numberWithCommas(val);
$('#tutar').text(val);
<table id="Piyasa" width="100%" cellspacing="0">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">Şirket</th>
<th scope="col">Alcaklı</th>
<th scope="col">Borçlanma Tarihi</th>
<th scope="col">Ödeme Tarihi</th>
<th scope="col">Tutar</th>
<th scope="col">Açıklama</th>
<th scope="col">Bilgi Güncelle</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="5" style="text-align:right" >Toplam:</th>
<th></th>
<th></th>
</tr>
</tfoot>
<tbody>
{% for musteri in piyasa %}
<tr>
<th scope="row">{{musteri.id}}</th>
<td>{{musteri.sirket}}</td>
<td><a href="/piyasa/details/{{musteri.id}}">{{musteri.alici}}</a></td>
<td>{{musteri.borc_tarih}}</td>
<td>{{musteri.odeme_tarih}}</td>
<td id="tutar">{{musteri.tutar|floatformat:2}}</td>
<td>{{musteri.aciklama}}</td>
<td><a href="/piyasa/update/{{musteri.id}}" >Güncelle</a></td>
</tr>
{% endfor %}
</tbody>
</table>
CodePudding user response:
The first thing you should do is not re-use the same id for multiple elements on the page, which you're doing inside your server-rendered loop building up table rows.
Instead use a class, and then use that class to target all the matching elements. In the example below I have used the class format-number
to indicate any cell I want to run the formatting code on.
function numberWithCommas(x) {
return "₺" x.toFixed(2).toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
}
$(".format-number").each(function(){
const $this = $(this);
const currentVal = parseFloat($this.text());
$this.text( numberWithCommas(currentVal) );
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td >10101.23</td>
</tr>
<tr>
<td >345678.56</td>
</tr>
<tr>
<td >123456789.45</td>
</tr>
</table>