Last active
June 8, 2022 18:13
-
-
Save brendomaciel/c7aef1d4d5f96ae3833b1cb592e49b36 to your computer and use it in GitHub Desktop.
Máscara de porcentagem utilizando o plugin jQuery Mask Plugin (limita o valor máximo a 100)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('#percent').mask('P', { | |
translation: { | |
'P': { | |
pattern: /[\d\.,]/, | |
recursive: true | |
} | |
}, | |
onKeyPress: function(val, e, field, options) { | |
var old_value = $(field).data('oldValue') || ''; | |
val = val.trim(); | |
val = val.replace(',', '.'); | |
val = val.length > 0 ? val : '0'; | |
// Transformando múltiplos pontos em um único ponto | |
val = val.replace(/[\.]+/, '.'); | |
// Verificando se o valor contém mais de uma ocorrência de ponto | |
var dot_occurrences = (val.match(/\./g) || []).length > 1; | |
// Verificando se o valor está de acordo com a sintaxe do float | |
var is_float = /[-+]?[\d]*\.?[\d]+/.test(val); | |
if (dot_occurrences || !is_float) { | |
val = old_value; | |
} | |
// Força o valor a ficar no intervalo de 0 à 100 | |
val = parseFloat(val) >= 100 ? '100' : val; | |
val = parseFloat(val) < 0 ? '0' : val; | |
$(field) | |
.val(val) | |
.data('oldValue', val); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment