Create a Javascript input Mask to accept values up to 4 decimals

Asked

Viewed 809 times

-1

Hi, I’ve been developing a website and I ran into a problem. I want to limit a textbox to accepting only 4 numbers after a "." (dot). I’ve done a lot of research, and I can’t find anything that makes my life any easier. I thought of a way to do it that would be to accept the numbers in the textbox without the writing position moving and after the user writes 4 numbers, automatically put a "." (point).

After this I need help figuring out how to start making the mask.

In advance, thank you.

  • There are plugins that facilitate this for you, one of them is jquery-Mask-money - https://github.com/plentz/jquery-maskmoney

1 answer

1


You don’t need scary plugins and you don’t need to use jQuery for something so trivial, you can do it by hand, learning the basics for real, of course.

An example of mask I made with pure JS helps understand how to do simply and even adapt later: /a/419538/3635, the process is basically timeout+regular expression+replace

Once this is done the question is the which you will need, in case there are four numbers after the point, so if you type up to 4 there is no point, I believe, so if you type 5 numbers it should be 9.9999, then the regex should look something like:

/^(\d+)(\d{4})$/

The first part of the regex ^(\d+) takes the digits that must come before the point and the (\d{4})$ takes the last 4 digits. Note that it is necessary .replace(/\D+/, ''); to remove what are not digits.

The code went like this:

document.addEventListener('DOMContentLoaded', function () {
    console.log('DOM carregou');
    
    var campo1 = document.getElementById('campo1');
    
    if (!campo1) return;
    
    var campo1Timeout;
    
    campo1.addEventListener('input', function () {
        if (campo1Timeout) clearTimeout(campo1Timeout);
        
        campo1Timeout = setTimeout(mascara, 200);
    });
    
    function mascara()
    {
         var value = campo1.value.replace(/\D+/, ''); //Remove tudo que não for numero

         value = value.replace(/^(\d+)(\d{4})$/, '$1.$2');      
         campo1.value = value;
    }
});
<input type="tel" name="campo1" id="campo1" placeholder="Seu numero">

  • Excellent! That’s what I wanted, but there’s a way to take that timeout and make it run in real time?

  • @Redcandy it avoids running multiple times without need, if within the time of 200ms (200 microseconds) you type again the Zera timer and starts again and does not perform the function, until you have actually typed everything, pq if it occurs to run several calls would get very slow and could even "crash"

  • Okay, I get it, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.