Sorry for the noob question but I am trying to apply this javascript function to data in an html table. The function comes from this Stack Overflow post.
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
I wish to apply this function to something like this:
<table>
<tr>
<td>5000</td>
<td>5600</td>
</tr>
</table>
with the hopes of returning 5,000 next to 5,600. I can’t figure out this simple thing. I know I need to use an id or class on one of the tags and that this needs to match something in the function so I tried
<table>
<tr class="numberWithCommas">
<td>5000</td>
<td>5600</td>
</tr>
</table>
to no avail. I’m sure the function works given the amount of upvotes.
Can a kind soul please walk me through the steps to make this work? I’ve googled all over for a basic tutorial and haven’t found anything.
You first need to get all the
tds, call the function on the content and insert the result back into the cell.HTML
Javascript
Demo
To explain all this code:
This is your function:
This allows us to get all the
tdwithin alltrs withnumberWithCommasas a class and sets them all as an array in the javascript variableelements:We then loop through the array accessing one
tdat a time:Inside the for loop we check that the value of the cell is not empty:
Inside the
ifstatement we call the functionnumberWithCommas()and pass it the value ofelements[i].innerHTML. We then get back the resulting string and apply it toelements[i].innerHTML: