我有一个文本字段,用户输入 SSN 号码。在进入自身时,它应该格式化。就像在更改 textField 时...它应该在显示器本身上以这种方式格式化 999-999-999
。
最佳答案
来自@kottenator 的脚本几乎就在那里,但它每 3 位数字打破一次值,而不是 3 位,然后 2 位,就像社会安全号码所需的 000-00-0000 一样。
我做了一些编辑并修改它以按预期工作。希望这会有所帮助。
<script type="text/javascript">
$('#ssn1').keyup(function() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
if(val.length > 4) {
this.value = val;
}
if((val.length > 3) && (val.length < 6)) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal.substring(0, 11);
});
</script>
关于javascript - 输入号码时自动格式化 SSN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7685175/