Reputation: 924
$("#txtField").keyup(function(){
let data = $(this).val();
//alert(data);
let splitData = data.split("-");
splitData[1] = "****";
splitData[3] = "*******";
if($(this).val().length == 19 && $(this).val().indexOf("-") > 0)
$(this).val(splitData.join("-"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="txtField" maxlength="19">
Sample Input
ABC-1234-11-1234567
I have this code above as example. But the problem here is that I can still see the 1234 upon inputting a text to the textbox. What I want to achieve here is that when I input the 1234 is it will automatically change into dot (like the type="password")
.
Note
Sample text above may change but the format is fix. It has three(3) dashes(-)
Expected Output
BLG-****-11- ******
Upvotes: 2
Views: 572
Reputation: 86
Another version you can try, using RegExp
:
//$('#txtField').on('keyup', function(){ // works
$('#txtField').on('input', function(){ // better
let s = this.value;
if (
/^(.{3}\-.{4}\-.{2}\-)(.{1,7})$/.test(s) ||
/^(.{3}\-)(.{1,4})$/.test(s)
) {
this.value = RegExp.$1 + RegExp.$2.replace( /./g, '*' );
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="txtField" maxlength="19">
And I totally agree with @User863 - using the input
event is better.
Upvotes: 2
Reputation: 20039
Using input
event.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event https://caniuse.com/#search=input%20event
$("#txtField").on('input', function() {
let data = $(this).val();
let splitData = data.split("-");
if (splitData[1])
splitData[1] = splitData[1].replace(/./g, '*');
if (splitData[3])
splitData[3] = splitData[3].replace(/./g, '*');
$(this).val(splitData.join("-"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="txtField" maxlength="19">
Upvotes: 1
Reputation: 36104
My suggestion is to prevent to use input
method because its new and not supported in all browsers reference, this is mostly same to @User863 user's answer, here i have used keyup
event, this is bit show a character when type in textbox and then after it will be convert into *
.
$("#txtField").on('keyup', function() {
let data = $(this).val();
let splitData = data.split("-");
if (splitData[1])
splitData[1] = splitData[1].replace(/./g, '*');
if (splitData[3])
splitData[3] = splitData[3].replace(/./g, '*');
$(this).val(splitData.join("-"));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<input type="text" id="txtField" maxlength="19">
Upvotes: 1
Reputation: 11416
You can do it like this using regular expressions:
$("#txtField").keyup(function() {
let data = $(this).val();
dots = data.replace(/\d+/g, "*");
$(this).val(dots);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtField"/>
Upvotes: 1