javascript - jQuery Mask Plugin: mask for negative integers -
i using jquery mask plugin in web project. used , don't want change now.
i use following mask numbers decimal separators:
for example element:
<input class="number-field" value="123456">
i use following mask:
$('input.number-field').mask('#,##0', {'reverse': true});
it works positive numbers, add support of negative numbers.
neither of following patterns work:
$('input.number-field').mask('#,##0z', { reverse: true, translation: { 'z': { pattern: /\-?/ } } }) $('input.number-field').mask('z#,##0', { reverse: true, translation: { 'z': { pattern: /\-?/ } } }) $('input.number-field').mask('z#,##0', { reverse: true, translation: { 'z': { pattern: /-/, optional: true } } })
last 1 seems working, 4 digits in line.
how can use plugin negative numbers? may consider patching plugin if can propose idea.
you can try jsfiddle template
i expanded off of last attempt , translated special #
character recursively accept digits , dashes (i.e., /[\d-]/
). changed masking pattern #,##0
.
since plugin doesn't allow add negative/positive lookaheads in regular expression pattern, added onchange
callback prevent -
characters being anywhere beginning of string.
.replace(/(?!^)-/g, '')
- remove of-
characters not @ beginning of line..replace(/^,/, '')
- remove leading,
characters (i.e., remove,
string,123
)..replace(/^-,/, '-')
- remove,
characters directly following-
characters (i.e., remove,
-,123
).
$('input.number-field').mask('#,##0', { reverse: true, translation: { '#': { pattern: /-|\d/, recursive: true } }, onchange: function(value, e) { e.target.value = value.replace(/(?!^)-/g, '').replace(/^,/, '').replace(/^-,/, '-'); } });
<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.13.4/jquery.mask.min.js"></script> <input class="number-field" value="123456">
additionally, if want prevent cursor indicator jumping end of string when replacing characters, leverage code other answer here.
$('input.number-field').mask('#,##0', { reverse: true, translation: { '#': { pattern: /-|\d/, recursive: true } }, onchange: function(value, e) { var target = e.target, position = target.selectionstart; // capture initial position target.value = value.replace(/(?!^)-/g, '').replace(/^,/, '').replace(/^-,/, '-'); target.selectionend = position; // set cursor initial position. } });
<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.13.4/jquery.mask.min.js"></script> <input class="number-field" value="123456">
Comments
Post a Comment