2017-04-27 54 views
0

這是HTML代碼:如何把破折號後的某一位是插入

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" class="telnumber" maxlength="20" /> 
 

 
<script> 
 
    $('.telnumber').keyup(function() { 
 
     foo = $(this).val().split("-").join(""); // remove hyphens 
 
     foo = foo.match(new RegExp('.{1,2}$|.{1,2}$|.{1,6}', 'g')).join("-"); 
 
     $(this).val(foo); 
 
    }); 
 
</script>

我想我的輸出這樣的528228-25-5258

+0

你能解釋一下嗎? –

+0

我想要我的輸出像這樣999999-99-9999 –

+0

大量的屏蔽腳本 – epascarello

回答

0

因此,對於以下解決方案,有幾個要點需要理解。

  • 首先,我改變了事件oninput從而使事件觸發時在文本框變化的投入,而不是當一個鍵被解除。

  • 二,而不是使用正則表達式,我只是使基於舊的,我們插入的字符串破折號如果它足夠長的一個新的字符串(6個或8個字符,根據您的規格)

  • 第三,我們將輸入分割成一個數組,然後在必要時插入連字符後重新加入。

這裏是解決方案: https://codepen.io/SammyIsra/pen/bWgWZq

+0

_「我希望我的輸出像這樣'528228-25-5258'。」_' javascript'在codepen允許輸入'099999-99-9999999999'。根據OP,這是否有效? – guest271314

+0

你是對的,我錯誤地忽略了輸入的長度。我修改了Codepen,它應該將輸入限制爲14位數(666666-22-4444) –

0

您可以使用pattern屬性與RegExp\d{6}-\d{2}-\d{4}匹配六位數字,然後破折號"-"後跟兩位數字後跟破折號"-"其次是四位數字; maxlength應設置爲14而不是20;將placeholder設置爲預期的.value999999-99-9999;使用input事件來檢查this.validity.patternMismatch,如果false,設置<input type="text">disabled,顯示在哪裏活動click<input type="text">.value設置頂空字符串""同級元素<input type="reset">。利用與for屬性相鄰的<label>元素設置爲id<input type="text">以向用戶顯示通知。

<!DOCTYPE html> 
 
<html> 
 

 
    <head> 
 
    </head> 
 

 
    <body> 
 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <input type="text" class="telnumber" id="tel" maxlength="14" pattern="\d{6}-\d{2}-\d{4}" placeholder="999999-99-9999"/><label for="tel">Invalid input <code>999999-99-9999</code></label> 
 
    <input type="reset"> 
 

 
    <script> 
 
     $(".telnumber").on("input", function(e) {  
 
      if (!this.validity.patternMismatch) { 
 
      this.labels[0].innerHTML = "Valid input"; 
 
      this.disabled = !this.validity.patternMismatch; 
 
      $(this).siblings("input[type=reset]").show().one("click", function() { 
 
       e.target.disabled = false; 
 
       e.target.value = ""; 
 
       e.target.labels[0].innerHTML = "Invalid input <code>999999-99-9999</code>"; 
 
       $(this).hide(); 
 
      }) 
 
      };   
 
     }).siblings("input[type=reset]").hide() 
 
    </script> 
 
    </body> 
 

 
</html>