It is necessary to catch the <select> change event when it changes programmatically

I have a selection on a page that converts to a slider using the Filament Group selectToUISlider .

Another script on the page is attached to the events of the exchange of form elements. Each time the user changes something, he recounts the result.

Now the problem here is that the onChange event does not fire when <select> when using the slider, since the value of <select> changed using the plugin.

Here's a script illustrating the problem: http://jsfiddle.net/t3aMe/

Is there a way to track the change in the selectedIndex selection? Or maybe there is a way to connect to the jQuery.val() function to make it trigger('change') ?

+4
source share
2 answers

Suppose you can overwrite the val function:

 (function ($) { var val = jQuery.fn.val; jQuery.fn.val = function () { var result = val.apply(this, arguments); if (arguments.length) { // eg if this is a "set" rather than a get this.filter('select').trigger('change'); }; return result; }; }(jQuery)); 

This will throw a change event for all select all elements on the page. You can add a massive hack:

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

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

+3
source

Just select the change event for the select element:

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

In your code example:

  (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);
+1
source

Source: https://habr.com/ru/post/1339334/


All Articles