2011-07-05 65 views
0

我正在處理表單,我想掩蓋電話號碼的輸入。我發現的插件對我來說不好,因爲區號可能是1或2個字符。 我想要做的是以下幾點: 當用戶在前兩個字符後鍵入他的編號時,腳本會在鍵盤上插入一個空格,然後在後面的三個字符之後插入一個空格,然後在每四個字符之後插入一個空格。 因此,當有人類型44444444444然後在文本框中出現44 44 444 4444 我必須檢查第二組爲好,例如當某人1種在那裏,數必須是這樣的:44 1 444 4444將特定字符後的空格插入到javascript字符串中

有任何解決方案來做到這一點?

+0

「我必須檢查第二組,以及當有人輸入例如1,數字必須如下:44 1 444 4444「,這種情況只適用於1嗎? – Qtax

回答

3

你可以做這樣的事情:

http://jsfiddle.net/ffwAA/4/

此功能適用於字符串,以獲得所需的格式:

function formatCode(str){ 
    var result = str; 

    str = str.replace(/\D+/g, ""); 
    var m = str.match(/^(\d\d)(?:([2-90]\d|1)(?:(\d\d\d)(\d+)?)?)?$/); 

    if(m){ 
     result = m[1] + " "; 
     if(m[2]) result += m[2] + " "; 
     if(m[3]) result += m[3] + " "; 

     if(m[4]){ 
      result += m[4].split(/(\d{4})/).join(" "); 
      result = result.replace(/\s+/g, " "); 
     } 
    } 

    return result; 
} 

並使用此jQuery來設置它:

function update(obj){ 
    var val = obj.value; 
    var got = formatCode(val); 

    if(got != val) 
     obj.value = got; 
} 

var timer; 
var prev_val = ""; 

$('#code').keyup(function(){ 
    clearTimeout(timer); 

    // when adding numbers at the end of input, update at once 
    // don't want to update when editing in the middle of the string or removing parts of it 
    // because it would move the carret location to the end of input, and make it unusable 
    if(this.value.indexOf(prev_val) == 0){ 
     update(this); 
     prev_val = this.value; 
     return; 
    } 

    prev_val = this.value; 

    // in other cases update 1 second after the changes are done 
    timer = setTimeout(update, 1000, this); 
}); 
+0

它的作品!!!!!非常感謝! – p8r

2

您是否嘗試過maskedInput插件?

http://digitalbush.com/projects/masked-input-plugin/

我認爲它可以解決你的問題。

希望這會有所幫助。乾杯

+0

是的,我試過,但問題是區號。有了這個插件,我可以將區號屏蔽爲兩個或一個字符。 :s – p8r

相關問題