Charas
Charas

Reputation: 1827

How to use jquery function on numbers separated by .(dot) or ,(comma) as thousands separator

I have a certain number and I use counter jquery function so that the number will animate from 0 to that number in a certain period of time. Now, the problem is when I add ,(comma) or .(dot) to the number as a thousand separator, it does not work. How do I make the script work with ,(comma) and .(dot) separator and get the result back with the ,(comma) and .(dot) too ?

html

<div class='number_container'>
    <span class='count'>317249</span>
</div>

css

.number_container {
    background: red;
    width: 100px;
    text-align: center;
    padding: 38px 0;
    border-radius: 50px;
    color: white;
    margin: 0 auto;
}

.count {
    font: 20px arial;
}

Js

$(document).ready(function() {
    $('.count').each(function() {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 3500,
            easing: 'swing',
            step: function(now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
});

Jsfiddle Preview

https://jsfiddle.net/y6zdmaeq/

I want the number 317249 to be displayed as 317,249 or 317.249 and count up from 0. Thank you

Upvotes: 1

Views: 2382

Answers (2)

Valath
Valath

Reputation: 920

I have coded html for your requirement. Please save this as an html file and please open it in browser. Please do vote if you like this. Please note that I have included an external plugin for the same."Happy coding!!"

<html>

<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="http://www.bendewey.com/code/formatcurrency/jquery.formatCurrency-1.4.0.js"></script>

</head>
<script>
  $(document).ready(function() {
    $('.count').each(function() {
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 3500,
        easing: 'swing',
        step: function(now) {

          $("#hiddenInput").val(Math.ceil(now).toString());

          var formattedText = $(".currency").formatCurrency().val();

          //alert(formattedText);
          $(this).text(formattedText);
        }
      });
    });
  });
</script>
<style>
  .number_container {
    background: red;
    width: 100px;
    text-align: center;
    padding: 38px 0;
    border-radius: 50px;
    color: white;
    margin: 0 auto;
  }
  .count {
    font: 20px arial;
  }
</style>

<body>

  <div class='number_container'>
    <span class='count '>317249</span>
    <input type="hidden" class="currency" id="hiddenInput"></input>
  </div>
</body>

</html>

Upvotes: 1

ntdat3011
ntdat3011

Reputation: 26

Combine with this answer and your code, just format code before .text()

https://jsfiddle.net/y6zdmaeq/2/

Upvotes: 1

Related Questions