5

I am using jQuery Mask Plugin in my web project. It is used widely and I don't want to change it for now.

I use the following mask for the numbers with decimal separators:

For example for the element:

<input class="number-field" value="123456">

I use the following mask:

$('input.number-field').mask('#,##0', {'reverse': true});

It works for positive numbers, but now I would like to add support of negative numbers.

Neither of the following patterns work:

$('input.number-field').mask('#,##0Z', {
  reverse: true,
  translation: {
    'Z': {
      pattern: /\-?/
    }
  }
})

$('input.number-field').mask('Z#,##0', {
  reverse: true,
  translation: {
    'Z': {
      pattern: /\-?/
    }
  }
})

$('input.number-field').mask('Z#,##0', {
  reverse: true,
  translation: {
    'Z': {
      pattern: /-/,
      optional: true
    }
  }
})

Last one seems working, but only for 4 digits in the line.

How can I use this plugin for negative numbers? I may consider even patching this plugin if someone can propose an idea.

You can try it with jsFiddle template

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
baldr
  • 2,891
  • 11
  • 43
  • 61

5 Answers5

12

I expanded off of your last attempt and translated the special # character to recursively accept digits and dashes (i.e., /[\d-]/). Then I changed the masking pattern to #,##0.

Since the plugin doesn't allow you to add negative/positive lookaheads in the regular expression pattern, I added an onChange callback to prevent - characters from being anywhere but the beginning of the string.

  • .replace(/(?!^)-/g, '') - This will remove all of the - characters that are not at the beginning of the line.
  • .replace(/^,/, '') - This will remove leading , characters (i.e., it would remove the , from a string like ,123).
  • .replace(/^-,/, '-') - This will remove , characters directly following - characters (i.e., it would remove , from -,123).

Updated Example

$('input.number-field').mask('#,##0', {
  reverse: true,
  translation: {
    '#': {
      pattern: /-|\d/,
      recursive: true
    }
  },
  onChange: function(value, e) {      
    e.target.value = value.replace(/(?!^)-/g, '').replace(/^,/, '').replace(/^-,/, '-');
  }
});
<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 class="number-field" value="123456">

Additionally, if you want to prevent the cursor indicator from jumping to the end of the string when replacing the characters, you could leverage the code from my other answer here.

$('input.number-field').mask('#,##0', {
  reverse: true,
  translation: {
    '#': {
      pattern: /-|\d/,
      recursive: true
    }
  },
  onChange: function(value, e) {
    var target = e.target,
        position = target.selectionStart; // Capture initial position

    target.value = value.replace(/(?!^)-/g, '').replace(/^,/, '').replace(/^-,/, '-');

    target.selectionEnd = position; // Set the cursor back to the initial position.
  }
});
<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 class="number-field" value="123456">
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • 2
    Thanks! Works fine! I only made some modifications to work with non-input elements too. Just check `$(target).prop("tagName") == 'INPUT'` and use `innerHTML` instead of `value` otherwise. – baldr Jan 07 '16 at 19:38
  • My only criticism is that in order to put in a negative number, you have to hit the [Home] key *after* you put in the raw numerical value, otherwise the `0` at the end of the mask (`#,##0`) prevents you from entering the negative value in any other way. I wish there was a way to capture any entered value *after* the first one entered, and if it is a negative sign, punt it to the front of the number. That way, you could enter “254-” and it would end up as “-254” automagically. Otherwise, excellent answer! Works for me. – René Kåbis Apr 19 '18 at 20:25
3

Just choose a character to translate signal, im my case Z.

$("#input").mask("Z0999999.00", {

   translation: {
     '0': {pattern: /\d/},
     '9': {pattern: /\d/, optional: true},
     'Z': {pattern: /[\-\+]/, optional: true}
   }

});

And put the mask on input.

<input id="input"/>
  • 1
    Does it work with a decimal separator? I would like to see the number "-123456789.12" as "-123,456,789.12". How do you do this? – baldr Feb 11 '17 at 12:22
  • To do it, you can use reverse input. But have a problem, you need to put the sign after input the number, moving the cursor to the first number character. look here : https://embed.plnkr.co/RnfflU31V0XMtO4CEgsm/ – Filipe Mendes Feb 12 '17 at 14:37
  • You can do a trick to put cursor in the first position and the sign character will work fine. look this plunkr, https://plnkr.co/edit/RnfflU31V0XMtO4CEgsm?p=preview – Filipe Mendes Feb 12 '17 at 14:57
0

If callback doesnt work you can

$(this).find("td.selling").each(function (i, element) {
        $(element).unmask().mask('###.###.###.###.###.###.###.###', {
            reverse: true,
            translation: {
                '#': {
                    pattern: /\-|\d/,
                    recursive: true
                }
            },
        });
        $(element).text($(element).text().replace('-.', '-'));
       
    });
ozn
  • 3
  • 2
0

/* For negative decimal values */

$('.money').mask("#.##0,00", {
  reverse: true,
  translation: {
    '0': { pattern: /\d/ },
    '#': {
      pattern: /\-|\d/, /*signal included*/
      recursive: true
    },
  }
});
-1

You can do this way:

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

If you use de charactere #, you can not initialize number with - therfore use 0 to translation

  1. value.replace(/^-\./, '-') This will change string like -. to -
  2. replace(/^-,/, '-') This will change string like -, to -
  3. replace(/(?!^)-/g, '') This will remove charactere - that are not at the beginning of the line
Austin
  • 2,982
  • 2
  • 28
  • 36