我要达到的目的是强制文本框以前缀(国家电话代码)开头并使其永久不变,这意味着用户无法绕过它。例如,“电话”文本框应始终以“+45”开头,然后用户可以添加电话号码。如何以任何方式防止其删除代码?
到目前为止,我使用jQuery做过的事情:
//attach event on phone text boxes
$(document).delegate(".phone", "keyup", function(event){
var target = $(this);
var value = target.val().trim();
if (value.indexOf(CONSTANTS.DANISH_PHONE_CODE) == -1) {
//country code not found
//if the user starts deleting the country code
if (value.indexOf("+") == 0){
value = "";
}
//if the user types something in front of the country code, put the country code at the end
value = value.replace(CONSTANTS.DANISH_PHONE_CODE, "");
//phone doesn't start with +45
value = CONSTANTS.DANISH_PHONE_CODE + value;
target.val(value);
}
});
但是问题是用户可以删除加号,并且前缀会自动放在开头,因此我们将获得+4545。您知道实现此目标的优雅方式吗?谢谢。
最佳答案
JSFiddle Example
这应该积极地阻止他们删除“+45”,而不是在用户更改问题后尝试解决该问题。按下按键时,确定字符位置,如果该位置在字符串中的位置太早(例如,在“+45”内部位于相反位置),则不允许按键,除非该键是向左或向右箭头键。
获得的资源:
http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea
Binding arrow keys in JS/jQuery