Search code examples
javascriptjqueryjasny-bootstrap

Clear (or change) input mask from input textbox (Using Jasny)


I wish to change the input mask on a textbox depending on the value selected on a select list. The code is:

$(document).ready(function () {
    $("#searchList").change(function () {
        $("#searchCriteria").val("");

        var value = $(this).find("option:selected").val();

        switch (value) {
            case "2":
                $("#searchCriteria").inputmask({ mask: '999999', placeholder: '' });
               break;
            default:
                alert('default'); // this alert pops up.
                $("#searchCriteria") ///I want to clear the mask here.
        }
    });
});

I have tried

$("#searchCriteria").unmask(); 

but get "Uncaught TypeError: $(...).unmask is not a function" error.

The documentation says '?' says 'any characters following will become optional' so I tried $("#searchCriteria").inputmask({ mask: '?', placeholder: '' });

with no success.

It does appear that once the mask has been set, it cannot be changed or cleared, but I'm sure there is a way.

I have also tried $("#searchCriteria").unbind();

Which cleared the mask, but would then not set it to anything else.

EDIT: I am not tied down to using Jasny, any other suggestions welcome :)

The requirement I'm trying to fulfil is 'Change an input mask on an input textbox according to the selection in a dropdown list'.


Solution

  • Found the answer from this SO question:

    How can I "reset" <div> to its original state after it has been modified by JavaScript?

    Essentially, store the cloned state in a variable, and use this variable to restore the element to it's original state before re-assigning the mask.

    The code now looks like this, switch statement has gone but that's for a non-related reason:

    $(document).ready(function () {
    
        var searchCriteriaClone = $("#searchCriteria").clone();
    
        $("#searchList").change(function () {
            $("#searchCriteria").val("");
            $("#searchCriteria").replaceWith(searchCriteriaClone.clone());
    
            var value = $(this).find("option:selected").val();
    
            if (value === "2") {
                $("#searchCriteria").inputmask({ mask: "999999", placeholder: "" });
            }
        });
    });