2012-12-28 86 views

回答

0

使用JavaScript和jQuery(如果你使用的常規的JavaScript,我認爲你需要使用的getElementById,谷歌它),並假設你的文本框被命名爲「文」:

http://api.jquery.com/keydown/

$('input[name=text]').keydown(function(event) 
{ 
    var text = this.val().replace("-",""); //get current text, take out the - 
    var strlength = text.length; 

    if (strlength >=10) //reached max length, ignore character   
    { 
     return false; // might be event.preventDefault(); 
    } 
    else if (strlength<5) //you want a letter 
    { 
     //if not a letter, cancel input 
     if (!(/^[a-zA-Z]+$/.test(String.fromCharCode(event.which))) return false; 
    } 
    else if (strlength>=5) //you want a letter 
    { 
     //if not a number, cancel input 
     if (!(/^[0-9]+$/.test(String.fromCharCode(event.which))) return false; 
     else if (strlength==5) this.val(text + "-"); //Add the hyphen 
    } 
}); 

可能需要編寫代碼來處理退格,但應該是不言自明/解釋