[英]Formatting HTML input text product key
我正在一个为Windows 7/8创建无人值守XML文件的网站上工作。
我进行了“产品密钥”文本输入,用户可以在其中输入产品密钥,并将其添加到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实现此功能的最简单方法是什么?
您可以模拟破折号,将其放在输入字段上,并添加onkeyup控件以添加空格,或jquery.maskedinput: http ://digitalbush.com/projects/masked-input-plugin/
有很多方法可以实现这一目标。 但是我要做的是每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;
}
然后,您要做的就是获取用户输入的产品密钥,然后将其通过“ split_product_key”传递:var splitted_product_key = split_product_key(original_product_key); 如果要实时更新值,只需在输入上添加一个更改,然后将输入值设置为split_product_key(current_input_value),希望这很清楚,希望对您有所帮助!
function split_product_key(t) {
t = t.toUpperCase();
var key = t.replace(/([\w]{4})([\w]{4})([\w]{4})([\w]{4})/, function(match, p1, p2, p3, p4, offset, string){
return [p1, p2, p3, p4].join('-');
});
return key;
}
这个使用正则表达式使16位字符串看起来像'NLEB-8KPR-RZR1-QWJF',编辑正则表达式部分以更改模式。 另外,这是一篇旧文章,但是我搜索了一个简单的解决方案,就是这样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.