将数字屏蔽到输入中的特殊字符(*) [英] masking numbers to a special character (*) in input
问题描述
我试图将SSN字段中的所有数字掩盖为*,同时保持用户只输入数值并用破折号格式化SSN。
这是一个小提琴链接:
<!DOCTYPE html>< html>< head> < script src =https://code.jquery.com/jquery-2.1.4.js>< / script> < meta charset =utf-8> < meta name =viewportcontent =width = device-width> < title> JS Bin< / title>< / head>< body> < input id ='ssn'maxlength ='11'/> <脚本> $(function(){$('#ssn')。keyup(function(){var val = this.value.replace(/ [^ \\ * *] / g,'').replace(/ \\ \\ d / g,'*'); var newVal =''; var sizes = [3,2,4]; var maxSize = 10; for(var i in sizes){if(val.length> sizes [i ]){newVal + = val.substr(0,sizes [i])+' - '; val = val.substr(sizes [i]);} else {break;}} newVal + = val; this.value = newVal;});}); < / script>< / body>< / html>
I am trying to mask all the numbers in SSN field to * while keeping user only enter numeric values and formatting the SSN with dashes.
Here is a fiddle link:
https://jsfiddle.net/7f8p83am/
$('#ssn').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
var sizes = [3, 2, 4];
var maxSize = 10;
for (var i in sizes) {
if (val.length > sizes[i]) {
newVal += val.substr(0, sizes[i]) + '-';
val = val.substr(sizes[i]);
} else {
break;
}
}
newVal += val;
this.value = newVal;
});
Obviously, the replace is getting rid of *. Any ideas on how to do this?
thanks in advance.
You could consider removing all non-digits and asterisks as they were entered and replacing digits with asterisk :
// Remove all non-digits/asterisks and replace digits with asterisks
var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g,'*');
Additionally, you may want to try adding a maxlength
attribute on your element as well to prevent it from continuing :
<input id='ssn' maxlength='11'/>
Finally, you will likely want to consider storing a hidden field or variable that will store your proper SSN value so that you can post it to the server as expected.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id='ssn' maxlength='11' />
<script>
$(function() {
$('#ssn').keyup(function() {
var val = this.value.replace(/[^\d\*]/g, '').replace(/\d/g, '*');
var newVal = '';
var sizes = [3, 2, 4];
var maxSize = 10;
for (var i in sizes) {
if (val.length > sizes[i]) {
newVal += val.substr(0, sizes[i]) + '-';
val = val.substr(sizes[i]);
} else {
break;
}
}
newVal += val;
this.value = newVal;
});
});
</script>
</body>
</html>
这篇关于将数字屏蔽到输入中的特殊字符(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!