2017年5月26日 星期五

【JQuery】Thousands separators

input text 千分位處理

直接看程式
  1. // Compatible with keyup
  2. function numberWithCommas(x) {
  3. return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  4. }
  5.  
  6. $(function () {
  7. // Init format after load
  8. $(".numberOnly").each(function () {
  9. $(this).val(numberWithCommas($(this).val()));
  10. });
  11. // Realtime format changing
  12. $(".numberOnly").keyup(function (event) {
  13. // skip for arrow keys
  14. if (event.which >= 37 && event.which <= 40) return;
  15. // format number
  16. $(this).val(function (index, value) {
  17. return value
  18. .replace(/\D/g, "")
  19. .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  20. });
  21. });
  22. });
  23.  
  24. $("#form1").submit(function () {
  25. // Remove commas before submit
  26. $(".numberOnly").each(function () {
  27. $(this).html($(this).html().replace(/,/g, ""));
  28. });
  29. return true;
  30. });

ref: Init partRealtime typing part

沒有留言:

張貼留言