使用jquery或纯javascript保留子字符串模式 [英] retaining substring pattern using jquery or plain javascript
问题描述
文本框具有存储具有类型电话号码或邮政编码的字符串的属性。
用户何时开始输入密钥应该以电话/邮政编码格式填充文本框。
例如 -
1st Pattern是234-23432,
2nd Pattern是(234) 24234-324。
所以当用户键入某些键时,字符应该相应排列。如果解决方案使用普通的JavaScript或jQquery,则无关紧要。
From page 。你可以使用下面的代码。你可以在 jsfiddle 上测试它。
$(function(){
$(input [name ='phone'])。keyup(function(){
var curchr = this.value.length;
var curval = $(this).val();
if(curchr == 3){
$(this).val((+ curval +)+ - );
} else if(curchr == 9){
$(this).val(curval + - );
}
});
});
A textbox has a property of storing a string which has a type telephone number or zip code.
Where and when a user starts typing the keys should fill the textbox in a telephone/zip code format. For example -
1st Pattern is 234-23432,
2nd Pattern is (234)24234-324.
So when user types in some keys the characters should be arranged accordingly. Does not matter if the solution uses plain JavaScript or jQquery
From page. you can use following code . you can test it on jsfiddle
$(function() {
$("input[name='phone']").keyup(function() {
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3) {
$(this).val("(" + curval + ")" + "-");
} else if (curchr == 9) {
$(this).val(curval + "-");
}
});
});
这篇关于使用jquery或纯javascript保留子字符串模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!