Search code examples
javascriptjqueryjquery-eventsmaskmasking

How to perform .select() on jQuery masked text input


I'm using http://digitalbush.com/projects/masked-input-plugin/ plugin.

There is an input text with defined mask:

<input type="text" id="txtMyInput" class="FocusSense"/>

and a script:

$(document).ready(function () {
    jQuery(function ($) {            
        $("#txtMyInput").mask("?9.99");            
    });
    $(".FocusSense").focus(function () {
        this.select();
    });
})

As you can see, I would like select all in txtMyInput on focus but but alas! On focus, mask appears and lose .select().

What should I do to preserve mask and .select()?


Solution

  • I think what you are looking for, is this :

    $(document).ready(function () {
        jQuery(function ($) {            
            $("#txtMyInput").mask("?9.99");            
        });
        $(".FocusSense").focus(function (e) {
          var that = this;
          setTimeout(function(){$(that).select();},10);
          return false;
        });
    });
    

    setTimeout will "queue" the select() execution. So it will select the content after masking is completed.

    Working Demo