Textfield to display number in REALTIME with CURRENCY FORMAT as you type IT. Exmple: 1,000.00

742 Views Asked by At

I have been trying to make this code to display textfield number in real-time currency format at you type it. But once the page is loaded, it give me an error message that say the following: Warning: number_format() expects parameter 1 to be double...

Please, can someone help me to fix the problem with the code. Below is my code.

            <input id="source" type="text" oninput="copyData('source', 'target')"  />
            
            <?php
            $num = '<span id="target" class="myDIV"></span>';
            $formattedNum = number_format($num, 2);
            echo $formattedNum;
            ?>
            
            <script type="text/javascript">
                  function copyData(sourceId, targetId) {
                    var data = document.getElementById(sourceId).value;
                    document.getElementById(targetId).innerHTML = data; 
                  }
            </script>
2

There are 2 best solutions below

4
On
  • Use jquery mask money library as in
    here.
  • You can find the example here.
  • Another example link is this.

Snippet example :

$(document).ready(function(){
  $('#maskmoney').maskMoney();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-maskmoney/3.0.2/jquery.maskMoney.min.js"></script>

<input id="maskmoney" name="mask_input" type="text">

0
On

You can't have live update with PHP. For this you'll need to use JS

PHP's number_format(number, n) can be replaced with JS's Number.toFixed(n)

function copyData(sourceId, targetId) {
  var data = Number(document.getElementById(sourceId).value);
  document.getElementById(targetId).innerHTML = data.toFixed(2); 
}
<input id="source" type="text" oninput="copyData('source', 'target')"  />
<span id="target" class="myDIV"></span>
            


You can go even further by using Intl.NumberFormat with style: 'currency' which will detect your user location and display the value in the user's regional format

function copyData(sourceId, targetId) {
  var data = Number(document.getElementById(sourceId).value);
  document.getElementById(targetId).innerHTML = new Intl.NumberFormat(undefined, { style: 'currency', currency: 'EUR' }).format(data); 
}
<input id="source" type="text" oninput="copyData('source', 'target')"  />
<span id="target" class="myDIV"></span>