user1893145 user1893145 - 20 days ago 8
HTML Question

Mask if more then x characters

I am using a masking plugin (http://digitalbush.com/projects/masked-input-plugin/) it works, but I am trying to get it to only work once there are 5+ characters in the textbox. Whenever I hit the 6th character, it clears out the textbox and won't accept input anymore.

JS:

<script>
function convert(){
if (l.length > 5){
$("#q").mask('(999) 999-9999');
}
}
</script>


HTML:

<form action="search.php" method="GET">
<input type="tel" class="form-control" name="q" id="q" placeholder="Phone/Order Number" onkeyup="convert()"><br>
<button type="submit" class="btn btn-default">Search</button>
</form>


if someone could please help me, that would be great. :D

Answer

It clears out the textbox because when you apply a mask, the plugin clears the input. You can get around this by passing the autoclear option and set it to false. It would also keep attempting to apply the mask, so you'd have to remove the event listener. So ditch the inline event handler, that's a bad way to do event handlers anyway :-)

Something like this would work:

$('#q').on('keyup', function() {
    var $el = $(this);
    var val = $el.val();
    if (val.length > 5){
        $el.mask('(999) 999-9999', {
            autoclear: false,
            placeholder: ''
        });
    }
});

Note that I also set the placeholder to an empty string, otherwise when the mask is applied the cursor will be set to the end of the mask placeholder and you'd have to move the caret back a few spaces.

Comments