JSFiddle - React, Tailwind, and code Playground
by joelpurra
HTML
<h1>
Trigger value change when the element updated by Val function
</h1>
<p>
<input id="my-text-box" value="Default Value" />
</p>
<p>
<Button id="poorly-designed">Example of a poorly designed plugin (triggers once)</button>
</p>
<p>
<Button id="well-designed">Example of a well designed plugin (triggers twice)</button>
</p>
<p>
This example shows that a properly designed plugin will trigger the .change() event twice, when it was only supposed to trigger it once. This can be fixed with proper filtering, so that if filters out the duplicate triggering either by callers (somehow) or by fields (with a whitelist of allowed inputs) in the extended .val() method.
</p>
<ul>
<li>Code from <a href="http://jqfaq.com/how-to-extend-a-jquery-method-to-inject-some-custom-functionality/">How to “extend” a jquery method to inject some custom functionality?</a></li>
<li>Example for <a href="http://stackoverflow.com/a/11114230/">Handle input text change event</a></li>
</ul>
CSS
h1 {
font-weight: bold;
}
p,
li {
margin-top: 0.5em;
}
input {
width:90%;
}
JavaScript
$(function() {
// Extending the val method so that the change event is triggered when value is changed using the val function.
// caching the val function.
var $valFn = $.fn.val;
$.fn.extend({
val: function() {
// Our custom val function calls the original val and then triggers the change event.
var valCatch = $valFn.apply(this, arguments);
if (arguments.length) {
$(this).change();
}
return valCatch;
}
});
var $input = $("#my-text-box");
$input.change(function() {
alert("change event triggered. Value is: " + $(this).val());
});
$("#well-designed").click(function() {
$input.val("Updated by a well designed plugin, which calls .val() and then .change()");
$input.change();
});
$("#poorly-designed").click(function() {
$input.val("Updated by a poorly designed plugin, which only calls .val()");
});
});