Xeptor Xeptor - 18 days ago 6
Javascript Question

Change string value by percentage dynamically

Im trying to change a strings number by percentage dynamically - but Im having no luck and now Im totally lost. How do I raise the number below with a given percentage, say 5%? Is this possible without having to rmove the spaces and the non-numeric characters?

<em class="number">13&nbsp;616:-&nbsp;<span class="status"></span></em>

Answer

Although not the best way, you can split too extract and make a proper number to do the calc on, and then rejoin..

Below is an example.

Personally, I would also save the number somewhere else, eg. maybe use a data attribute.

$('button').click(function () {
  $('.number').each(function () {
    var num = $(this),
      splits = num.html().split('&nbsp;'),
      splits2 = splits[1].split(':'),
      val = (Math.round((splits[0] + splits2[0]) * 1.05)).toString();
    splits[0] = val.substring(0,val.length-3);
    splits2[0] = val.substr(-3,3);
    splits[1] = splits2.join(':');
    num.html(splits.join('&nbsp;'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<em class="number">13&nbsp;616:-&nbsp;<span class="status"></span></em><br/>
<em class="number">12&nbsp;216:-&nbsp;<span class="status"></span></em><br/>
<em class="number">15&nbsp;002:-&nbsp;<span class="status"></span></em>



<button>Raise 5%</button>

Comments