1

I want to format all input type numbers into comma separated value, I found the code for conversion over the net but it is not working in the fashion I want, it should convert all the input number into a specific format.

I also tried, doing type text but it still wont work.

$(document).ready(function() {
  $(".number").each(function() {
    var _val = $(this).val();
    $(this).val(_val.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="locationError" class="number" type="text" value="1221312321" readonly/>
<input name="locationError" type="text" value="1221312321"  class="number" readonly/>

This is different since i want it on document on load

SCS
  • 1,162
  • 3
  • 17
  • 31

1 Answers1

1

Change type="number" to type="text" or type="currency" inside your html.

Also remember, to change the jquery selector to $("input[type='text']") or $("input[type='currency']") for working in your particular snippet scenario!

$(document).ready(function() {
  $("input[type='text']").each(function() {
    var x = $(this).val();
    alert(x);
    $(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="locationError" type="text" value="1221312321" />
<input name="locationError" type="text" value="1221312321" />
Iceman
  • 6,035
  • 2
  • 23
  • 34
  • 1
    maybe i did not include the jquery when testing the code in jsfindle.. but thanks – SCS Jul 23 '16 at 22:24
  • 1
    added a class number instead of text to have unique – SCS Jul 23 '16 at 22:26
  • Much better. I just was replicating from your snippet and editting the least, for a minimal changed answer. – Iceman Jul 23 '16 at 22:27
  • Did you know you could use [`.toLocaleString()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString) to add commas instead of using regex? `var val = parseFloat(this.value).toLocaleString();` – Mottie Jul 23 '16 at 22:34