Why does the jquery change event not trigger when I set the value of a select using val()?

后端 未结 9 949
猫巷女王i
猫巷女王i 2020-11-22 09:34

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse

9条回答
  •  感动是毒
    2020-11-22 10:19

    I ran into the same issue while using CMB2 with Wordpress and wanted to hook into the change event of a file upload metabox.

    So in case you're not able to modify the code that invokes the change (in this case the CMB2 script), use the code below. The trigger is being invoked AFTER the value is set, otherwise your change eventHandler will work, but the value will be the previous one, not the one being set.

    Here's the code i use:

    (function ($) {
        var originalVal = $.fn.val;
        $.fn.val = function (value) {
            if (arguments.length >= 1) {
                // setter invoked, do processing
                return originalVal.call(this, value).trigger('change');
            }
            //getter invoked do processing
            return originalVal.call(this);
        };
    })(jQuery);
    

提交回复
热议问题