tbrutsm1
tbrutsm1

Reputation: 21

Replace inner html with value of html time a value using JQuery

I am working with an HTML table structure that contains values of text and integer. My goal is to identify which cells contain integer values and replace them with their value times -1. For instance:

This Year | 5 | 4 | -12

Last Year | 2 | 2 | 20

Would be updated to:

This Year | -5 | -4 | 12

Last Year | -2 | -2 | -20

Ideally, I would accomplish this with one line of JavaScript/jQuery. The line I am working with is:

$(".value-cell").filter(function( index ) {return $.isNumeric($(this).text());}).text(parseFloat($(this).text())*-1);

However, this line just fills the cells with NaN. I have tried a few variations of this but have not been able to accomplish what I am looking for.

UPDATE:

I should note, the filtration is working as expected and hitting the cells I want it to. I believe the problem lies with accessing $(this) in the text assignment, however, I am unsure of how else to access the text of the HTML element to multiply by -1.

Upvotes: 2

Views: 70

Answers (1)

spanky
spanky

Reputation: 2870

Pass a function to .text() to have it operate on each element.

$(".value-cell").filter(function(index) {
  return $.isNumeric($(this).text());
}).text(function(i, txt) {
  return parseFloat(txt) * -1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=value-cell>abc</div>
<div class=value-cell>123</div>

And if you don't need the filtered set after this, you can get rid of the .filter() call and make the new value conditional.

$(".value-cell").text(function(i, txt) {
  return $.isNumeric(txt) ? parseFloat(txt) * -1 : txt;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=value-cell>abc</div>
<div class=value-cell>123</div>

And of course, a modern syntax solution with no jQuery dependency could look like this:

for (const el of document.querySelectorAll(".value-cell")) {
  const t = el.textContent;
  el.textContent = !t || isNaN(t) ? t : +t;
}
<div class=value-cell>abc</div>
<div class=value-cell>123</div>

Upvotes: 2

Related Questions