没有插件的 Javascript 输入文本屏蔽 [英] Javascript Input Text Masking without Plugin

查看:18
本文介绍了没有插件的 Javascript 输入文本屏蔽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不更改实际值的情况下屏蔽输入框中的文本.我不能使用任何插件.

I want to mask the text in an input box without changing the actual value. I can not use any plugins.

我目前正在这样做 - 但正如您所看到的,问题是实际值在提交时发生了变化.我怎样才能改变显示值?

I am currently doing this - but as you can see the issue is that the actual value is changed on submit. How can I just change the display value?

$("input[name='number']").focusout(function(){
    var number = this.value.replace(/(d{2})(d{3})(d{2})/,"$1-$2-$3");
    this.value = number;
}

推荐答案

你需要两个输入

两个输入应该可以完成工作.一个输入将包含掩码文本,另一个将是包含真实数据的隐藏输入.

You need two inputs

Two inputs should get the job done. One input will contain the masked text and the other will be a hidden input that contains the real data.

<input type="text" name="masknumber">
<input type="text" name="number" style="display:none;">

我处理屏蔽的方法是构建一个用于屏蔽和取消屏蔽内容的函数,以便一切保持统一.

The way I approached the masking is to build a function for both masking and unmasking the content so everything stays uniform.

$("input[name='masknumber']").on("keyup change", function(){
        $("input[name='number']").val(destroyMask(this.value));
    this.value = createMask($("input[name='number']").val());
})

function createMask(string){
    return string.replace(/(d{2})(d{3})(d{2})/,"$1-$2-$3");
}

function destroyMask(string){
    return string.replace(/D/g,'').substring(0,8);
}

这篇关于没有插件的 Javascript 输入文本屏蔽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆