簡體   English   中英

在用戶鍵入時動態格式化文本字段

[英]Format text field as user is typing, dynamically

我有一個text_field_tag ,允許用戶輸入金額。 在用戶鍵入時,如何動態設置此值的格式? 例如,如果用戶輸入“ 5000”,則它必須顯示為“ 5,000”。

如果您以直接的方式考慮,我們可以將當前的val替換為格式化后的值。 在這種情況下,即使多次使用for循環(在格式化和反格式化之間),性能也不昂貴。

對於替換文本,我不使用正則表達式,因為我們需要從右邊查找/匹配文本,因此,要使用正則表達式,我認為我們需要先反轉文本,應用正則表達式替換並將結果反向。 這比簡單地循環和替換要糟糕得多。

這是代碼:

HTML

<input type="text"/>
<button> Show value </button>

JS

var format = function(text) {
  var f = "";
  for(var i = text.length - 1; i >=0; i--){
    f = text[i] + f;
    var k = text.length - i;
    if(k % 3 == 0 && i > 0){
      f = "," + f;
    }
  }
  return f;
}
//defomratting the text to get the actual value
var deformat = function(text) {
  return text.replace(/,/g, "");
}

$("input").on("input", function(e){
  var s = this.selectionStart;
  var rawVal = $(this).val();
  var clen = rawVal.length;
  val = deformat(rawVal);
  var f = format(val);
  s += f.length - clen;
  $(this).val(f);
  //set the selection to ensure that it's not changed during typing.
  this.selectionStart = this.selectionEnd = s;
});

$("button").click(function(){
  alert(deformat($("input").val()));
});

演示版

您可以使用真正易於集成的Jquery Mask插件,它將帶來許多您可以使用的面具。 也將節省大量時間。

$('.money').mask('000.000.000.000.000,00', {reverse: true});

https://igorescobar.github.io/jQuery-Mask-Plugin/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM