0

I want to change the format of an amount when a client writes for example 1200100.22 input change format by 1,200,100.22 $.

$('#prix').bind('change', function(){
    var nStr = $(this).val();  
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    console.log(x1 + x2);
    $prix = x1 + x2;
    $("prix").val($prix);
  });
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>rules</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>
</head>
<body>
<div class="container">
    <form id="myform">
    <div class="form-group">
      <label>prix <span class="text-hightlight">*</span></label>
      <input type="text" name="prix" id="prix" class="form-control"/>
    </div>
    <button class="btn btn-theme">valider</button>
    </form>
 </div>

</body>
</html>
Andreas
  • 21,535
  • 7
  • 47
  • 56
marzouk najib
  • 71
  • 2
  • 10

1 Answers1

-1

If you are using jQuery, use the input mask plugin.

$('input[name="prix"]').mask('000,000,000,000,000.00$', {
  reverse: true
});
<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.mask/1.14.16/jquery.mask.min.js"></script>

<div class="container">
  <form id="my-form">
    <div class="form-group">
      <label>prix <span class="text-hightlight">*</span></label>
      <input type="text" name="prix" id="prix" class="form-control" />
    </div>
  </form>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132