2013-03-08 30 views
0

我在一個爲Windows 7/8創建無人蔘與XML文件的網站上工作。格式化HTML輸入文本產品密鑰

我做了一個「產品密鑰」文本輸入,用戶可以在其中輸入產品密鑰,並將其添加到XML中,以便在安裝過程中不會收到提示。

這是我迄今爲止:

<td>Product Key:</td> 
<td><input id="ProductKey1" size="5" maxlength="5" type="text">-<input id="ProductKey2" maxlength="5" size="5" type="text">-<input id="ProductKey3" maxlength="5" size="5" type="text">-<input id="ProductKey4" maxlength="5" size="5" type="text">-<input id="ProductKey5" maxlength="5" size="5" type="text"></td> 

我已經基本加入5個的文本輸入具有5個字符的最大長度,並且每個字段由「 - 」分隔。

我想要做的是有一個產品密鑰的更長的字段,並讓它在每5個字符後插入「 - 」。用javascript實現這個最簡單的方法是什麼?

+1

你嘗試過什麼嗎? http://stackoverflow.com/faq – Kyborek 2013-03-08 14:51:00

回答

0

有很多種方法來實現這一目標。但我會做的是「substr」字符串每5個字符。我會做這樣的:

function split_product_key(t) { 
    // How many characters in string 
    var length = t.length; 
    // How many "5 chars length strings" is there in your string 
    var loop = Math.ceil(length/5); 
    // Create the output. 
    var output = ''; 
    for (var i =1; i<=loop; i++) { 
     // Getting the 5 chars substr 
     output += t.substr((i*5),5) + '-'; 
    } 
    // Removing the last "-" 
    output = output.substr(0, output.length-1); 
    return output; 
} 

然後,所有你需要做的就是獲取用戶輸入產品密鑰,並通過它throught「split_product_key」是這樣的: VAR splitted_product_key = split_product_key(original_product_key); 如果您想實時更新這些值,只需在輸入上添加一個更改並設置輸入值split_product_key(current_input_value) 我希望這很清楚,我希望它能幫上忙!