SCS SCS - 4 months ago 15
Javascript Question

format type number with comma on page load

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

Answer

$(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" />

Comments