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

后端 未结 9 879
猫巷女王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:08

    To make it easier add a custom function and call it when ever you want that changing the value also trigger change

    $.fn.valAndTrigger = function (element) {
        return $(this).val(element).trigger('change');
    }
    

    and

    $("#sample").valAndTirgger("NewValue");
    

    Or you can override the val function to always call the change when the val is called

    (function ($) {
        var originalVal = $.fn.val;
        $.fn.val = function (value) {
            this.trigger("change");
            return originalVal.call(this, value);
        };
    })(jQuery);
    

    Sample at http://jsfiddle.net/r60bfkub/

提交回复
热议问题