javascriptjquerymaskedinputjquery-mask

get rid of x if no extension given for phone field in Jquery masked input plugin


Im using jquery Masked input plugin.

I have the following mask on a field:

 "?999-999-9999 x9999"

Why ? in begining? because if user entered incomplete number, i dont want the field to clear out so i made the whole thing optional. now when user is entering the numbers is able to see x always whether or not a phone has extension. How do i get rid of that x if no extension was given?

Again i do not want to clear out the field, if i use

  "999-999-9999? x9999" 

yes it works it adds x only when it has extension but if incomplete phone entered it empties the field which is not the goal.

Any help is appreciated thanks alot.


Solution

  • after trying alot i fixed it myself to accomplish the goal.

    Goal was to keep text not disappearing if incomplete input was given and to get rid of x if no extension was given.

    I added this test at the end of code:

    var splitString = $("[name=myinput]").val().split("x");
    //if splitString array length is more than 1 means splitString[1] is set
    //if splitString[1].length is 0 means its only x by itself so get rid of it
    if (splitString.length > 1 && splitString[1].length == 0) {
        $("[name=myinput]").val($("[name=myinput]").val().replace("x", ""));
    }
    

    examples:

     entered text: 718-111-123 x -> turns into -> 718-111-123
     entered text: 718-111     x -> turns into -> 718-111
     entered text: 718-111-123 x555 -> turns into -> 718-111-123 x555