How to apply masking in a textbox

Viewed 112

I have a grid in which there is a textbox that is currently accepting numeric numbers. However I want to apply masking in that textbox using javascript or jquery without any plugin. I have searched and everywhere they are asking for plug-in.

I tried this solution but it does not work my default value should be 00000-00-000

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

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

Any help would be appreciated.

1 Answers

Add a hidden input which will store original value without masking.

Html:

<input type="text" value="0000000000" id="masknumber">
<input type="text" id="numberWithoutMask" style="display:none;" value="0000000000">

JS:

// call function on change
$("#maskNumber").on("keyup change", function () {
    updateValue();
})
// function to update the value with masking
function updateValue() {
    $("#numberWithoutMask").val(destroyMask($("#maskNumber").val()));
    $("#maskNumber").val(createMask($("#numberWithoutMask").val()))
}

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

function destroyMask(string) {
    return string.replace(/\D/g, '').substring(0, 10);
}
updateValue(); // call function to update the default value

If you're loading default value, load value to both the inputs.

Related