I was successful in restricting the 3 figures after the decimal places however the fix is not working when i copy paste some random decimal figures into the text field.
$('.min-val').on('keyup', function(e) {
$(this).val($(this).val().replace(/[^\d.]/g, ''));
if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
$(this).val($(this).val().substring(0, $(this).val().length - 1));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" />
How can i restrict the decimal figures to 3 even when i copy paste the data?
You can achieve this with regex itself. I am not good at it though.
So below work around works.
You can determine the number of characters to trim and use that number
var charsToTrim = $(this).val().split('.')[1].length - 3;
$('.min-val').on('keyup', function(e) {
$(this).val($(this).val().replace(/[^\d.]/g, ''));
if ($(this).val().indexOf(".") > -1 && ($(this).val().split('.')[1].length > 3)) {
var charsToTrim = $(this).val().split('.')[1].length - 3;
$(this).val($(this).val().substring(0, $(this).val().length - charsToTrim));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" placeholder="min val" class="min-val" />
Tags: input, jqueryjquery, rest