3

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.

3
  • Do you want formatted value with 00000-00-000, right? Commented Dec 18, 2020 at 7:10
  • Does this answer your question? Javascript Input Text Masking without Plugin Commented Dec 18, 2020 at 8:38
  • @Adhitya no it does not answer my question. My textbox value should show by default this format 00000-00-000 and user can only enter in this format. Commented Dec 18, 2020 at 12:47

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What's your requirements??
Because this is a duplicate post.
I checked that post when you commented. Btw my code is very different from that. And for masking input values, this is the only way without using any plugin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.