0

I want to format with comma a number what a value of input. But, This code is not working. jquery version is 3.6.0.

$(function(){
  $('.bid_btns_add button').on('click',function(){
    var current_value = parseInt($('#bid_price').attr('value'));
    var add_value = parseInt($(this).val());
    var total_value = current_value + add_value;

    var output_value = total_value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); //error               
    var output_value = total_value.toLocaleString(); //error

    $('#bid_price').attr('value', output_value);
  });
  $('.bid_btn_clear').on('click',function(){
    $('#bid_price').attr('value',0);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>

<div class="bid_btns_add">
  <button type="button" class="" value="1000">1000</button>
  <button type="button" class="" value="5000">5000</button>
  <button type="button" class="" value="10000">10000</button>
</div>

<input id="bid_price" type="number" class="input_price" value="0"></input> 
<button type="button" class="bid_btn_clear">x</button>
Peter Krebs
  • 3,831
  • 2
  • 15
  • 29
  • 2
    `var x = 1234; x.toLocaleString()` works fine (try it in the console). number.replace will give the error *".replace is not a function"* - you have to convert it to a string first, eg `var x = 1234; x.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");` which also works fine. – freedomn-m May 03 '22 at 09:03
  • 2
    Hi I have edited your snippet and added jQuery. There was also a missing `
    ` which I added for you so the error will show. See comment above, you must convert the number to a string.
    – Peter Krebs May 03 '22 at 09:04
  • 1
    Also: `$('#bid_price').attr('value', output_value);` is not how you update an input: `$("#bid_price").val(output_value)` – freedomn-m May 03 '22 at 09:05
  • This might be related [Rounding with `.toFixed()`](https://stackoverflow.com/questions/72025417/javascript-max-4-digits-after-comma/72026094#72026094) – Peter Krebs May 03 '22 at 09:07
  • Could you please show your wanted result? – Huy Phạm May 03 '22 at 09:07

0 Answers0