[英]Add a permanent prefix to a textbox
What I am trying to achieve is to force a textbox to start with a prefix ( country telephone code ) and to make this permanent, meaning that the user cannot bypass this. 我要达到的目的是强制文本框以前缀(国家电话代码)开头并使其永久不变,这意味着用户无法绕过它。 For example, the Phone textbox should always start with "+45" and after that the user can add the phone number.
例如,“电话”文本框应始终以“ +45”开头,然后用户可以添加电话号码。 How to prevent it from deleting the code, by any means?
如何以任何方式防止其删除代码?
What I done so far, using jQuery: 到目前为止,我使用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);
}
});
But the problem is that the user can delete the plus sign and the prefix is put automatically at the start so we will have +4545. 但是问题在于用户可以删除加号,并且前缀会自动放在开头,因此我们将获得+4545。 Do you know an elegant way of achieving this?
您知道实现此目标的优雅方法吗? Thanks.
谢谢。
You can absolutely position the text (in a span) over the textbox and add a left-margin to it. 您可以将文本绝对地(跨度)放置在文本框上,并向其添加左边界。
This way users won't be able to remove it. 这样,用户将无法删除它。 But you'll have to add it server side.
但是您必须在服务器端添加它。
Add the +45 as static html before the field. 在字段前添加+45作为静态html。 Required the user to enter "the rest" of the number (not the +45).
要求用户输入数字的“其余”(不是+45)。
If necessary, add the +45 server side before persisting the value. 如有必要,请在保留该值之前添加+45服务器端。 Similarly, remove the +45 when editing.
同样,编辑时请删除+45。
This should actively keep them from deleting "+45" instead of trying to fix the problem after the user as changed it. 这应该积极阻止他们删除“ +45”,而不是在用户更改问题后尝试解决该问题。 Upon keypress, determine character position, if the position is too early in the string (ie inside the "+45" as oppose to after it) then don't allow the keypress, unless that key is the left or right arrow keys.
按下按键后,确定字符位置,如果该位置在字符串中的位置太早(例如,在“ +45”内部位于相反位置),则不允许按键,除非该键是向左或向右箭头键。
Acquired resources: 获得的资源:
http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea Binding arrow keys in JS/jQuery http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea JS / jQuery中的绑定箭头键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.