【问题标题】:Masking inputs any field and values屏蔽输入任何字段和值
【发布时间】:2018-02-27 01:42:13
【问题描述】:

我想知道如何获取输入的长度并替换值 start 和 end 之间的所有内容,但保留 2 个字符和两端。

我不想预定义长度,因为我希望它可以处理具有任何值的任何输入,并且在提交表单时仍然能够使用 PHP 读取值。

输入: Hello world street 12 输出: He*** ***** ****** 12

输入: 185445414631 输出: 18********31

Js 库: https://github.com/igorescobar/jQuery-Mask-Plugin

我的代码: https://jsfiddle.net/k4y0ctho/1/

【问题讨论】:

  • 屏蔽字符串,保留前 2 个字符和后 1 个字符。这就是模式吧。?
  • @HimanshuUpadhyay 前 2 和后 2 先生
  • 字符串总是有数字,也可以是字母,如示例所示?
  • @HimanshuUpadhyay 两位先生

标签: jquery html masking


【解决方案1】:

如果您的输出在其他领域是可以接受的,这可能会有用

$("#input").on("keyup", function() {
 
  var input = $(this).val().split("")
  var res = $.map(input, (el, ix) => {
    return ix < 2 || ix > input.length - 3? el:"*"
  })

  $("#output").html(res.join(""));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="password" id="input" />
<br><span id="output"></span>

【讨论】:

  • 这是一个好的开始,我现在拥有的更好,但它应该与掩蔽相反:)
【解决方案2】:

如果你使用 jQuery,你可以做的是:

// Util function to mask the value
function maskValue(value) {
    if (typeof value !== 'string' || value.length <= 4) {
        return value;
    }
    return value.split('').map((v, i) => { return (i > 1 && i < value.length - 2 ? '*' : v); }).join('');
}

// actual value (not masked)
let actualValue = '';

// keyup event to handle new input and mask the value
$("#my-input").on("keyup", function(event) {
    if (event.key === 'Backspace') {
        actualValue = actualValue.substring(0, actualValue.length - 1);
    }
    else {
        actualValue += event.key;
    }
    $('#my-input').val(maskValue(actualValue));
});

请记住,这并不完美,因为它只支持普通键(字母、数字、符号)和退格键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多