简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM