2015-06-15 22 views
-2
<td> 
    <input type="text" id= "test" name="test" size="22" maxlength="22" value="" onkeypress="onsplkeypressTest()" > 
</td> 
function onsplkeypressTest() { 
    var _newVal = document.getElementById("test").value; 
    _newVal = _newVal.split(' ').join(''); 
    var len = _newVal.length+4; 
    var ind = 4; 

    while (ind < len){ 
     _newVal = _newVal.substring(0, ind) + ' ' + _newVal.substring(ind, len); //add space 
     ind = ind + 5; 
    } 

    document.getElementById("test").value = _newVal; 
} 

這使輸出ABCD IJKL NOPQ 但是如果我想在ABCDIJKL之間進入EFGH它不會允許 它 - 它在最後被追加:ABCD IJKL NOPQ EFGHonkeypress事件4字符後添加空格

應該寫什麼代碼才能輸出ABCD EFGH IJKL NOPQ

+0

你在尋找什麼來格式化信用卡號碼? – naomik

+0

沒有我的要求是既可以在單一的文本框中輸入文字像第四個字符後,這個 安其按自動空間應該得到補充 ABCD EFGH IJKL MNOP 和用戶可以從任何位置 編輯或有四個文本框 ,如果用戶複製完整的16位數字並粘貼到第一個文本框中 剩餘文本應該添加到第二,第三和第四個文本框中 –

回答

0

將事件更改爲onkeyDown,這有助於跟蹤哪個鍵被按下。

下一個event.jeycode給出的關鍵代碼,13爲輸入和8爲後退空間,對於這些按鈕,您的代碼不應執行。

<input type="text" id="test" name="test" size="22" maxlength="22" value="" onkeydown="onsplkeypressTest()" /> 


<script type='text/javascript'> 
     function onsplkeypressTest(e) { 
      if (event.which == 13 || event.keyCode == 13) { 
       //code to execute here 
       return true; 
      } 
      else if (event.which == 8 || event.keyCode == 8) { 

      } 
      else { 
       var _newVal = document.getElementById("test").value; 
       _newVal = _newVal.split(' ').join(''); 

       var len = _newVal.length + 4; 

       var ind = 4; 

       while (ind < len) { 

        _newVal = _newVal.substring(0, ind) + ' ' + _newVal.substring(ind, len);//add space 

        ind = ind + 5; 

       } 

       document.getElementById("test").value = _newVal; 
      } 
     } 
    </script> 
+0

即使此代碼也會在字符串的末尾添加新文本,而不是在兩者之間 –