Search code examples
jquerymaskedinput

Mask Text is missing, when Setting .val(null) or .val('')


I'm using a date format, which naturally only allows numbers. I set up some shortcuts on such fields where 'd' or 't' defaults to current datetime, and 'c' clears back to null.

When clearing via .val(null) or val(''), the text box ends up completely empty - the inputmask plugin doesn't automatically replenish the mask.

This is likely a bug, but I would like a workaround.


Solution

  • The documentation mentions:

    set the value by using the value property and after that trigger the setvalue event

    Looking in the source code, I found this refers to

    .triggerHandler("setvalue.inputmask")
    

    But that didn't work. However, if I click off and then on again, the mask would be replenished. Therefore I added the following code after assigning the value:

    $(element).val(dateString); // Assigning the value
    if (dateString === null && $(element).is(":focus")) // If already focused
    {
        $(element).focus(); // Refocus to replenish mask
    }