Please tell me, if you change the field value in the middle, then the onchange function does not work. If you write numbers at the end, then the function works. The problem is only in the safari browser. What could be the problem?
jQuery.fn.extend({
phone: function() {
var maskList = [{
"code": "+7 ### ### ## ##",
"country": "RU"
},
{
"code": "+380 ## ### ## ##",
"country": "UA"
}
];
var change = function(e) {
if (e.type == 'paste') $(this).val('');
cursor_start = $(this).prop('selectionStart');
cursor_end = $(this).prop('selectionEnd');
let matrix = '###############';
if ($(this).val()[0] == '+') {
matrix = '+##############';
}
maskList.forEach(item => {
let code = item.code.replace(/[\s#]/g, ''),
phone = $(this).val().replace(/[\s#-)(]/g, '');
if (phone.includes(code)) {
matrix = item.code;
}
});
let i = 0,
val = $(this).val().replace(/\D/g, '');
value = matrix.replace(/(?!\+)./g, function(a) {
return /[#\d]/.test(a) && i < val.length ? val.charAt(i++) : i >= val.length ? '' : a;
});
if (val.replace(/\D/g, '').length > value.replace(/\D/g, '').length) {
value += val.replace(/\D/g, '').slice(value.replace(/\D/g, '').length);
}
$(this).val(value);
return this;
}
return this.each(function() {
$(this).on('load keyup paste', change);
$(this).trigger('load');
});
}
});
$(".phone").phone();
$(".phone").on("change", function() {
console.log("change");
})
$(".no_phone").on("change", function() {
console.log("change");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="phone" value="+380000000000">
<input type="text" class="no_phone" value="123">
P.s Only open in safari.
This does not work only for the field on which this function is hung. Other field normally fulfills onchange.
IOS tends to not fire change events when you change the value of their inputs.
If you change onchange to onblur it works for iOS but not others. The fix I eventually came to was to use BOTH onblur and onchange. Seems redundant but has the desired effect.
$(".phone").on("change blur", function() {
console.log("change");
})