2011-07-07 15 views
1

我有兩個面具G999-9和H99-9代表畢業生和榮譽,這兩個面具都需要爲單個輸入文本html控件輸入。Masked編輯單個輸入文本框的兩種代碼格式

第一次打字時,如果打到G,我希望它顯示畢業格式的格式,對於榮譽,我希望它在輸入時顯示榮譽格式的格式。有沒有簡單的方法來在JavaScript或jQuery中做到這一點?

例子:

 
G111-1 
H91-5 
G001-3 
G___-_ (If you hit G it should show the Graduate format) 
H__-_ (If you hit H it should show the Honors format.) 
____-_ (Type anything else, or nothing do this.) 

感謝, 馬克

回答

3

Regex Based Demo

耶!正則表達式!是的,像所有其他(非HTML)解析問題一樣,這是一個正則表達式。 :)

$("input").keyup(function(e){ 
    if(e.keyCode > 40 || e.keyCode < 37) 
    { 
     var validInput = $(this).val().match(/(([G])(([0-9]{3}[-]([0-9]{0,1})?|[0-9]{0,3})?)?|([H])(([0-9]{2}[-]([0-9]{0,1})?|[0-9]{0,2})?)?)/); 
     $(this).val(validInput?validInput[0]:"") 
    } 
}); 

這有點複雜(幫助優化它將不勝感激),但它的工作原理。

+1

+1不僅需要時間來建立rege x,但爲了幫助說明我的觀點,即正則表達式會是令人討厭的。 :) –

+2

@John Green約定的XD,但它很有趣!這幾乎就像一個數學謎題XD –

+1

我真的希望這適用於顯示錯誤後的格式。如果留下格式並且人們在鍵入時鍵入實際格式的類型,那將很酷。通常,當某人開始輸入時,格式會被刪除。 – RetroCoder

2

簡單的方式?你要麼必須走字符串,要麼使用一些奇特的正則表達式。

通常情況下,我們會使用正則表達式來解決這個問題,但是假設您對正則表達式不太瞭解(也許是一個糟糕的假設,但大多數人可以先閱讀它們),並且在讓你下面發生了什麼希望,我寫的程序上多:

<input type="text" class="formatted" /> 

$(document).ready(function(){ 
    function applyMask(instr){ 
     var pOut = [], delimitter = '-', format = 0, pSplit = 4, pMax = 6; 
     // There are a lot of ways to express this. I just chose one that should 
     // be understandable. 
     if ((instr.length > 0) && (instr[0].toUpperCase() == 'H')) 
     { 
      pSplit = 3; 
      pMax = 5; 
     } 
     pMax = Math.min(pMax, instr.length); 

     for (var i=0; i < pMax; i++) 
     { 
      if ((i==pSplit) && (instr[i] != delimitter)) 
      { 
       pOut.push(delimitter); 
      } 
      else 
      { 
       pOut.push(instr[i]); 
      } 
     } 
     return pOut.join(''); 
    } 

    $('.formatted').keyup(function(){ 
     $(this).val(applyMask($(this).val()).toUpperCase()); 
    }); 
}); 

這裏有一個小提琴,甚至:http://jsfiddle.net/UdcND/