jquery.maskedinput programmatically set value and apply mask?

13,131

Solution 1

Perhaps things have changed since this question was asked, because Jason P's first suggestion appears to work now.

$('#txt_PhoneNumber').trigger('input');

jsfiddle

The following should work too:

$('#txt_PhoneNumber').trigger('paste');

Solution 2

I was able to get it to refresh by calling .trigger("focus") : JSFiddle

The downside: it highlights the input.

Share:
13,131
Corey Ogburn
Author by

Corey Ogburn

Updated on July 23, 2022

Comments

  • Corey Ogburn
    Corey Ogburn almost 2 years

    I'm using DigitalBush's MaskedInput jquery plugin. I have a simple input box for a phone number:

    $('#txt_PhoneNumber').mask('(999) 999-9999');
    

    Sometimes the field is programmatically filled with a non-formated number such as 5551234567. How can I notify the mask input to apply it's mask to "beautify" it's new input?

  • Tim TJey Jun
    Tim TJey Jun about 8 years
    Really strange behaviour, i changed your code ( not using Math.random, just simple text ) , and it stoped working $("#txt_PhoneNumber").val(function(index,val){ return 10 * 10; }).trigger("focus");
  • Jackson Cassimiro
    Jackson Cassimiro over 7 years
    $('#txt_PhoneNumber').trigger('input'); works for me.
  • Tom Regan
    Tom Regan over 6 years
    I need to support IE 11 and Chrome v64.0. In IE 11 .trigger('input') is all that is needed. In Chrome 64.0 I find I need .trigger('input').trigger('focus').
  • Garland Pope
    Garland Pope over 5 years
    If the phone number value is blank, .trigger('input') leaves it as "(___) ___-____" instead of blank. Reapplying the mask with .mask('(999) 999-9999') does the trick.