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

查看:95
本文介绍了没有插件的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天全站免登陆