javascript將數字四位分隔模擬銀行卡號碼程式碼例項

admin發表於2017-04-12

如果大家觀察仔細,就會發現銀行卡的上號碼都是每四位一分隔。

這麼做當然是很人性化的,如果是一長串排列下拉,那可讀性簡直差的沒法形容。

下面就分享一個能夠實現此功能的程式碼:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript">
function func (BankNo){
  if (BankNo.value == "") return;
  var account = new String(BankNo.value);
  /*帳號的總數, 包括空格在內 */
  account = account.substring(0,22); 
  if (account.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
    /* 對照格式 */
    if (account.match(".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|"
      + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|"
      + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}|"
      + ".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
      var accountNumeric = accountChar = "", i;
      for (i=0;i<account.length;i++){
        accountChar = account.substr (i,1);
        if (!isNaN(accountChar) && (accountChar != " "))
          accountNumeric = accountNumeric + accountChar;
      }
      account = "";
      for (i=0;i<accountNumeric.length;i++){
        if (i == 4) account = account + "-"; /* 帳號第四位數後加空格 */
        if (i == 8) account = account + "-"; /* 帳號第八位數後加空格 */
        if (i == 12) account = account + "-";/* 帳號第十二位後數後加空格 */
        account = account + accountNumeric.substr (i,1)
      }
    }
  }else{
    account = " " + account.substring(1, 5)
      + " " + account.substring(6, 10)
      + " " + account.substring(14, 18)
      + "-" + account.substring(18, 25);
  }
  if (account != BankNo.value) BankNo.value = account;
}
function checkBankNo (BankNo){
  if (BankNo.value == "") return;
  if (BankNo.value.match (".[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{7}") == null){
    if (BankNo.value.match ("[0-9]{19}") != null)
      func (BankNo)
  }
}
function checkEnterForFindListing(e){
  var characterCode;
  if(e && e.which){
    e = e;
    characterCode = e.which ;
  }
  else{
    e = event;
    characterCode = e.keyCode;
  }
  if(characterCode == 22){
    document.forms[getNetuiTagName("findListingForm")].submit();
    return false;
  }
  else{
    return true ;
  }
}
window.onload = function () {
  var otxt = document.getElementById("account");
  otxt.onkeyup = function () {
    func(this);
  }
}
</script>
</head>
<body>
<input type="text" size="25" id="account"/>
</body>
</html>

相關文章