Trigger input event automatically on value changed with code

The event on input field gets triggered only when we type in the text box. But what if we change the input textbox value by javascript. That won't trigger the input event. Here the example to understand the behavior.
$("#textbox").on('input', function() {
  alert($(this).val());
});

$('#btn').click(function() {
  $("#textbox").val($("#textbox").val() + '_newvalue');
});

<input id="textbox" type="text" />
<button id="btn">Change</button>
<script src="jquery.min.js"></script>

Here the event is triggered when we type in input with id textbox.  But it doesn't get triggered when button with id btn is clicked. So here we would like to achieve a way so that the input event gets triggered even when the value is changes via jquery method. We could also trigger the input event manually but that would be an extra overhead. That would lead to an extra statement addition whever there is a dynamic value change.
There might be a case where you have a lot of input fields and you change those programmatically at multiple places.

So a solution to this is to override  jQuery's val() method. We can add the code to automatically trigger input event  whenever the val method is called. Below is the piece of code that works.


(function ($) {
    var originalVal = $.fn.val;
    $.fn.val = function (value) {
        var res = originalVal.apply(this, arguments);

        if (this.is('input:text') && arguments.length >= 1) {
            // this is input type=text setter
            this.trigger("input");
        }

        return res;
    };
})(jQuery);

Here is JSFiddle Demo for your reference.

So this is a solution that I could suggest. Feel free to suggest a better solution if any.
Hope you liked reading my post. I would love to get your valuable feedback in for of of comments.
Happy coding!

Related

technology 5889455377405648969

Post a Comment

emo-but-icon

 

Recent Posts

comments

Join Us

 

Recommended

get social

item