MAZ
MAZ

Reputation: 214

Replace dot by comma on Json Data content

I'm extracting a percentage data using a json file and displaying it on my web site :

<?php
    $resultData = file_get_contents('https://example.com/json/stats?_l=en');
    $jsonData = json_decode($resultData, true);
    if( isset( $jsonData["stats"] ) && !empty($jsonData["stats"]) ){
    
        foreach( $jsonData["stats"] as $stat ){                 
            echo "<div class='stat-item'>".$stat["item_example"]." % My Data displaying here </div>";
        }           
    }
?>

I'm trying to replace the "dot" with a "comma" in the displayed percentage. Example replace 5.5 with 5,5

I'm trying to do it with the following Javascript

<script>
    $(document).ready(function () {
        $('.stat-item').keyup(function () {
            var content = $(this).val();
            $(this).val(content.replace(/[\.]+/g, ','));
        });
    });
</script>

Upvotes: 0

Views: 918

Answers (2)

Lelio Faieta
Lelio Faieta

Reputation: 6689

There is no need to build the dom with php and then manipulate it with javascript (btw with the wrong event handler). I'd do it on the php side, using number_format

So your php would become:

echo "<div class='stat-item'>".number_format($stat["item_example"],2,",",".")." % My Data displaying here </div>";

In this example you are limiting to 2 decimal places the numbers returned, you are using , as decimal separator instead of the dot you get now, and you are using . as the thousands separator (for info only since I don't expect your figures to get higher than 100)

Upvotes: 1

Dario
Dario

Reputation: 6280

You should not use val() but text() instead; also is not clear why you need keyup event on the div. I would just write:

$(".stat-item").each(function () {
  var content = $(this).text();
  $(this).text(content.replace(/[\.]+/g, ","));
});

Upvotes: 1

Related Questions