Percentage Mask

0

I need a percentage mask with the jQuery Mask Plugin v1.5.4 library.

What I'm trying to do is that the user can report a value from -99.99 to 99.99.

I'm trying like this:

$("#edtPercentual").mask("99,99%");

$("#edtPercentual").on("blur", function() {
    var value = $(this).val().length == 1 ? $(this).val() + '%' : $(this).val();
    $(this).val( value );
});

As you can see, it does not deal with much. How do I get negative and also how do I get "%" in any situation, in the above code the percentage does not appear when the value has two (2) decimal places.

    
asked by anonymous 10.08.2017 / 14:34

3 answers

2

Using the base of the response from @LucasCosta, I changed to the form I needed:

  • Removed% of mask and assigned to blur and focus triggers

$('.numero').mask('Z#9V##', {
    translation: {
		'Z': {
		  pattern: /[\-\+]/,
		  optional: true
		},
		'V': {
		  pattern: /[\,]/
		},
		'#': {
		  pattern: /[0-9]/,
		  optional: true
		}
	}
});

$(".numero").on('blur',function(){
	if($(this).val().length > 0)
	   $(this).val( $(this).val() + '%' );
}).on('focus',function(){
	  $(this).val( $(this).val().replace('%','') ); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.3/jquery.mask.min.js"></script>

<input class="numero" />
    
10.08.2017 / 16:10
1

You can use translate :

$('.numero').mask('Z99,99%', {
  translation: {
    'Z': {
      pattern: /[\-\+]/,
      optional: true
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.3/jquery.mask.min.js"></script>

<input class="numero" />
    
10.08.2017 / 14:42
1

An alternative would be to do this:

jQuery(function($){
  $("#edtPercentual").keyup(function() {
    //Obter o primeiro caractere digitado
    var temp = $(this).val().charAt(0);
    //Verificar se o primeiro caractere inserido é '-'
    if (temp == '-'){
        //Aplica a máscara para números negativos
        $("#edtPercentual").mask("-99,99%");
    }
    //Verificar se o primeiro caractere inserido é número
    else if (temp.charAt(0).match(/\d/)){
        //Aplica a máscara para números positivos
        $("#edtPercentual").mask("99,99%");
    }
    //Caso o primeiro caractere inserido seja um caractere inválido limpa o value do campo
    else {
       $("#edtPercentual").val('');
    }
  });  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.3/jquery.mask.min.js"></script>
Percentual <input type="text" id="edtPercentual">
    
10.08.2017 / 14:55