Kalashir Kalashir - 3 months ago 11
Javascript Question

jquery-InputMast overriding existing events on input field

In below code I have attached onChange() event on id "phone_world" and also applying input mask on it.
Input mast is working fine but removing existing event and hello function is not getting called.

<div class="demo">
<input type="text" id="phone_world" onChange = "hello()" value="" size="25">
<label for="phone_world" id="descr_world">Страны мира</label>




<script>
var listCountries = $.masksSort($.masksLoad("https://cdn.rawgit.com/andr-04/inputmask-multi/master/data/phone-codes.json"), ['#'], /[0-9]|#/, "mask");

var maskOpts = {
inputmask: {
definitions: {
'#': {
validator: "[0-9]",
cardinality: 1
}
},
showMaskOnHover: false,
autoUnmask: true,
clearMaskOnLostFocus: false
},
match: /[0-9]/,
replace: '#',
listKey: "mask"
};
var maskChangeWorld = function(maskObj, determined) {
if (determined) {
var hint = maskObj.name_ru;
if (maskObj.desc_ru && maskObj.desc_ru != "") {
hint += " (" + maskObj.desc_ru + ")";
}
$("#descr_world").html(hint);
} else {
$("#descr_world").html("Страны мира");
}
}
$('#phone_world').inputmasks($.extend(true, {}, maskOpts, {
list: listCountries,
onMaskChange: maskChangeWorld
}));
function hello(){
alert('hi');
}
</script>

Answer

According to the jQuery input mask multi's docs, the keydown, keypress, paste, input, dragdrop, drop & blur events are interrupted, however it seems like the change event is interrupted as well (and not documented). What you can do is bind the focus and blur events to check for the change (with some help of the data() function to save the changes and compare them).

Here is a sample of the code:

$('#phone_world')
    .on('focus', function() {
        $(this).data('original-val', $(this).val())
    })
    .on('blur', function() {
        if ($(this).data('original-val') != $(this).val()) {    
            alert('value changed')
        } else {
            alert("value wasn't changed")
        }
    });

Here is a working fiddle: https://fiddle.jshell.net/5a6xo8kc/