I'm trying to add dots to separate thounsands in html input tags of type number. It works only for numbers of 6 digits, after adding one more digit to the input, the number disapears.
Here is the code
js
$(document).on("change", 'input[type="number"]', function () {
const inputSelectors = $('input[type="number"]')
inputSelectors.mask("000.000.000.000.000.000", {reverse: true});
})
html
<input name="detail-unit-price" type="number" step="any" value="0" required>
I've tried commenting every other javascript line to make sure that the problem is related only to this method and the problem persists. If I omit the .mask() method, everythong works perfectly.
CodePudding user response:
Because you use attribute type="number"
it will only accept numbers, such as 123.456
. The default number representation is to use the .
dot for decimal separator, and ,
for magnitude indication. It looks like you want to reverse that, which is not supported by type="number"
. That means, you can use that attribute.
Here is a solution that does not have the type="number"
attribute, and adds the .
for magnitude indication using regex instead of the .mask()
jQuery plugin. Note that the "change"
event only fires on focus loss, not on content change.
$(document).on("change", '.detail-input', function () {
let val = $(this).val();
val = val
.replace(/(\d)(\d{15})$/, '$1.$2')
.replace(/(\d)(\d{12})$/, '$1.$2')
.replace(/(\d)(\d{9})$/, '$1.$2')
.replace(/(\d)(\d{6})$/, '$1.$2')
.replace(/(\d)(\d{3})$/, '$1.$2');
$(this).val(val);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="detail-unit-price" value="0" required>