Case 1:
You want to change the value programmatically yourself and just want to dispatch an event when the value is changed.
$('#myfield').text('New value');
//$('#myfield').val('New value');
$('#myfield').trigger('change');
Case 2:
Suppose, you want to detect the programmatic change to a field which is not written by you. So, there is no way you can trigger 'change' event.
In this case, Use 'DOMSubtreeModified' to detect programmatic changes to descendant elements of a parent element.
Example:
<div id="product-addons-total">
<div id="total_price">200</div>
</div>
$(document).ready(function() {
jQuery('#product-addons-total').on("DOMSubtreeModified",function(){
console.log('content changed');
//tamp_price_change_handler();
});
});
Now, if the value of the "total_price" changes somehow programmatically, it will fire "DOMSubtreeModified" event.
Example:
jQuery('#total_price').text('300');
Caution for Case 2: DOMSubtreeModified can create an infinite loop and greatly degrade performance. Instead, it is encouraged to use MutationObserver.
Example with MutationObserver:
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// Let's configure the observer
var config = { childList: true, subtree:true, attributes: true, characterData: true,
characterDataOldValue: true, attributeOldValue: true };
//Let's get a node.
var target = jQuery('#product-addons-total').get(0);
// Let's pass the target and configuration to the observe function.
observer.observe(target, config);
Case 3:
The above ways can detect a change in the DOM. But if you want to change the value of an input field programmatically, then these events won't fire. In that case, the only way is to trigger an event manually.
So, first change the value of an input field and then trigger an event manually.
$('#inputfield').val(456465).trigger('change');
//Now the change event will fire.
$('#inputfield').on('change', function() {
console.log('input filed has been changed');
});