开发者

Need to catch <select> change event, when it changes programmatically

开发者 https://www.devze.com 2023-02-09 18:22 出处:网络
I have a select on a page, which is transformed into slider using Filament\'s Group selectToUISlider.

I have a select on a page, which is transformed into slider using Filament's Group selectToUISlider.

Another script on a page is attached to onchange events of the form elements. Every time user changes something, it recalculates the result.

Now here's the problem - onChange event doesn't fire for <select> when you use the slider, since <select> value is changed using plugin.

Here's the fiddle to illustrate the problem: http://jsfiddle.net/t3aMe/

Is there a way to monitor a change in selectedIndex of a select? Or maybe there's a way to plug into jQuery.val() function to make it tr开发者_如何转开发igger('change')?


I suppose you could overwrite the val function:

(function ($) {
  var val = jQuery.fn.val;

  jQuery.fn.val = function () {
    var result = val.apply(this, arguments);

    if (arguments.length) {  // e.g if this is a "set" rather than a get
      this.filter('select').trigger('change');
    };

    return result;
  };
}(jQuery));

This will trigger the change event for alll select elements in the page, though. You could add a massive hack:

if (arguments.length) {  // e.g if this is a "set" rather than a get
  this.filter('select#select_test').trigger('change');
};

Working fiddle: http://jsfiddle.net/t3aMe/2/


Just trigger change event on select element:

$('#select_test').trigger('change');

In your example code:

(function($) {
    $('#select_test').change(function() {
        $('#debug').text('onChange: new value: ' + $(this).val());
    });

    $('#change_select').click(function(e) {
        e.preventDefault();

        var newv = parseInt($('#select_test').val()) + 1;
        $('#select_test').val(newv > 3 ? newv - 3: newv);

        $('#select_test').trigger('change');
    });
})(jQuery);
0

精彩评论

暂无评论...
验证码 换一张
取 消