1

I have an updateable list

<ul>
  <li>
    <a class="one">posts <span class="num_1">1</span></a>
    <a class="two">followers <span class="num_2">999</span></a>
    <a class="three">following <span class="num_3">1K</span></a>
  </li>
</ul>

<button class="post-btn">Post</button>
<button class="follow-btn">Follow</button>

if a user updates the list by clicking either button and the number is below 1000, i want to get the text and add or subtract 1. if the number is above 1000, hence 1K, i want nothing to happen. all i have so far is this code which works for numbers under 1000 and not numbers abbbreviated as 1K

$('.num_1').text(Number($('.num_1').text())+1); or $('.num_1').text(Number($('.num_1').text())-1);

any help would be appreciated thanks

Max Njoroge
  • 489
  • 3
  • 21
  • 1
    *if the number is above 1000, hence 1K, i want nothing to happen. all i have so far is this code which works for numbers under 1000 and not numbers abbbreviated as 1K?*....contradictory requirements! – Mamun Jan 17 '21 at 10:18
  • Does this answer your question? [Check if string contains only digits](https://stackoverflow.com/questions/1779013/check-if-string-contains-only-digits) – freedomn-m Jan 17 '21 at 10:21
  • you will also need to multiply the number by 1000, if there is a **K** in the line. And after that, do the check. – s.kuznetsov Jan 17 '21 at 10:50
  • Translating the postfixes `k`, `m` or `g` (for "kilo", "mega" and "giga") is not so complicated, but unfortunately, that won't be enough if you want to then imcrement these values. You would need to have all digits of these number available, otherwise the incrementation will not be successful. – Carsten Massmann Jan 17 '21 at 16:04
  • @freedomn-m yes thanks that helps – Max Njoroge Jan 18 '21 at 04:12

1 Answers1

1

The numeric value of strings such as "1k" or "1m" is NaN.

Therefore, you may use Number.isNaN method to determine whether the string should be updated. for example:

function increase (elem) {
    var previousValue = Number(elem.text());
    if (!Number.isNaN(previousValue)) {
        elem.text(previousValue + 1);
    }
}

increase($('.num_1'))
noam gaash
  • 337
  • 2
  • 13