How to sum a filtered html table?

前端 未结 2 1998
一个人的身影
一个人的身影 2021-01-17 05:22

I have a HTML Table that I am able to filter with jquery. At the bottom of my table, i want to have a "total" row, that sums all values displayed. The sum displaye

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 05:34

    You can query the DOM and filter by attr as follows:

    Array
    .from(document.querySelectorAll('table#datatable td')) // Or some other selector you wish
    .filter(r=>r.hidden) // Enter here your filter func. Can also filter by `r.style.display` etc.
    .reduce((sum, curr)=>sum+(Number(curr.innerHTML) || 0), 0) // Here we try to get the value of the td. If it will resolve to NaN ==> We will return 0 and won't affect the value.
    

    This will yield the sum you desire. Place that value wherever you want then :)

    Resources:

    1. Array.from()
    2. Array.prototype.filter()
    3. Array.prototype.reduce()

提交回复
热议问题