Javascript input mask with negative decimal

Asked

Viewed 1,444 times

1

I took this code here from the forum, but I’m having doubts about using negative numbers.

The user needs to type 1° the negative sign and then the numbers. Certain results will be negative others will not, so it needed a way that the user could type first the sign and then the numbers.

Follows code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>
<script language="javascript" type="text/javascript">

$('.numerico').mask('#.##0', {
     reverse: true,
     translation: {
        '#': {
            pattern: /-|\d/,
            recursive: true
        }
     },
     onChange: function(value, e) {
        e.target.value = value.replace(/(?!^)-/g, '').replace(/^,/, '').replace(/^-,/, '-');
     }
});

</script>

1 answer

0


In the mask you need to have the identification of the sign as optional and this is identified with the letter N in configuration translation, and thus have the option to type numbers with the negative sign, example:

$('.numerico').mask('N#.##0', {
    translation: {
        'N': {
            pattern: /[-]/,
            optional: true
        }
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.13.4/jquery.mask.min.js"></script>

<input type="text" class="numerico" />

  • 1

    Thank you Virgilio, it worked super well with this code. m/

Browser other questions tagged

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