user1893145 user1893145 - 1 year ago 76
HTML Question

Mask if more then x characters

I am using a masking 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.


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


<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>

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download