Arton Hoxha
Arton Hoxha

Reputation: 373

Input formatting jQuery

I am using this plugin: jQuery-Mask-Plugin to format inputs.

I got it working but the problem is that i want to have a range that begins from 0.0 to 6.0 maximum. It means when i put 6 i can only write 6.0 and no 6.1 or 6.3,... It is the same with 0.

demo

$('#test_numeral').mask('a.9', { 'translation': { a: { pattern: /[0-6]/ } } });
<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.14.15/jquery.mask.js"></script>
<input type="text" id="test_numeral">

Is there a way to make it work with this plugin or do you know such plugins that can do this thing?

Upvotes: 0

Views: 357

Answers (2)

Alex
Alex

Reputation: 2232

As Pavan Sikarwar pointed out, it's great to use a callback function.

CodePen Link

Pretty much same script as above but instead of setting the value to 6.0, I made is so that you can't type the last decimal.

let opts = {
  'translation':
  {
    a:  
    {
      pattern: /[0-6]/
    }
  },
  onKeyPress: function(cep, event, currentField, options){
    if(cep > 6.0) { currentField.val('6.'); }
  }
}

$('#test_numeral').mask('a.0', opts);

Upvotes: 0

Pavan Sikarwar
Pavan Sikarwar

Reputation: 798

You can use callback function and change its value if greater than 6.0

$('#test_numeral').mask('a.9', {
    'translation': {
        a: {
            pattern: /[0-6]/
        }
    },
    onKeyPress: function(cep, event, currentField, options) {
        if (cep > 6) {
            currentField.val('6.0');
        }
    }
});
<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.14.15/jquery.mask.js"></script>
<input type="text" id="test_numeral">

Upvotes: 3

Related Questions