Search code examples
jquerymaskmasking

jQuery Dynamic Masking


I have used jQuery Masking plugin in my App.

Link is given here.

https://github.com/digitalBush/jquery.maskedinput

I need the dynamic masking like.

Sometime I will need to use like this 000-00-0 0000000-00-0

Suppose I write 50000 then it would become 50-00-0

Suppose I write 500000 then it would become 500-00-0

So my first section will contain 1 to 7 different numbers.

So how i can do this.

Simple masking i am using like in below.

$("input[name='mask']").mask("9999999-99-9");

Solution

var my_condition = true;
    $("input[name='mask']").on('click focus', function(){ 
       $("input[name='mask']").unmask();
       my_condition = true;
    });  
    $("input[name='mask']").on('change paste', function() {
        var len = $(this).val().length;
            if(my_condition) {
             switch(len) {
                 case 5:
                     $("input[name='mask']").mask('99-99-9');
                     break;
                 case 6:
                     $("input[name='mask']").mask('999-99-9');
                     break;
                 case 7:
                     $("input[name='mask']").mask('9999-99-9');
                     break;
                 case 8:
                     $("input[name='mask']").mask('99999-99-9');
                     break;
                 case 9:
                     $("input[name='mask']").mask('999999-99-9');
                     break;
                 case 10:
                     $("input[name='mask']").mask('9999999-99-9');
                     break;
                 default:
                      $("input[name='mask']").mask('9999');   
             }
             my_condition = false;
         }
    });

Thanks


Solution

  • I've written a simple JSFiddle to demonstrate how would I tackle that problem.

    Here is my JS code:

    $("#input").change(function(){
     var len = $(this).val().length;
    
    
    if(len == 4)
        $(this).mask('99-99');
    else if (len == 5)
      $(this).mask('999-99');
    else if (len == 6)
      $(this).mask('9-99999');
    })
    
    $("#input").focus(function(){
     var val = $(this).val().replace("-",""); //remove the dashes from the old masked value
     $(this).mask("9999999999"); //set to maximum length
     $(this).val(val);
    })
    

    The problem with .mask() is that it sets a maximum length for the input field which means that if you set a mask "99-99", you can't write more than 4 digits in the input field.My solution is to set the mask to "9999999999" when the input gets focused then set the proper mask after changing the value. You'll have to change the change() (accidental pun) event to fit your needs.

    Implementation flaw: User cannot see mask while typing