簡體   English   中英

有什么方法可以檢測和更改輸入值格式?

[英]Is there any way to detect and change the input value format?

我正在使用正則表達式檢查和驗證文本區域的值,並且我想更改如下格式:用戶輸入:

123456

改成:

12/34/56

可以用純js完成嗎?

編輯:

這是我所做的:

 function changeIt() {
  var inputChanger = document.getElementById("id").value.replace(something , something);
  document.getElementById("id").value = inputChanger;
}

但不知道如何進行

嘗試這樣的事情:

注意:要使此代碼正常工作,HTML必須在JavaScript之前,但是堆棧溢出顯然會重新排序代碼段以始終首先顯示JS(?)。

 var input = document.getElementById('my-input'); function format() { // \\d matches a digit, // parenthesis let you use the matched values as $n in the replacement string input.value = input.value.replace(/(\\d\\d)(\\d\\d)(\\d\\d)/, '$1/$2/$3'); } // you probably only need one of these, but it doesn't hurt to have both input.addEventListener('change', format); input.addEventListener('keyup', format); 
 <input type="text" id="my-input" /> 

當然,它也可以使用一些jQuery以及http://jquery-plugins.net/maskjs-jquery-plugin-to-mask-inputs之類的插件來完成-但我認為最好了解該工具下發生了什么引擎蓋,即使您最終會那樣走。

暫無
暫無

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

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