Antonio
Antonio

Reputation: 931

How to bind a function to a select when is changed regardless how

I want to bind a function to a select with javascript. I can do it with onchange or .change(). However, it seems that my function is not being triggered if the change has done programmatically:

e.g.

<select id='selectId' onChange;"javascript:console.log('changed - onchange')">
jQuery( "#selectId" ).change(function() {
   console.log( "changed - .change()" );
});

jQuery('#selectId').val("2").change()      //(a)
jQuery('#selectId').val("1");              //(b)

If the user changes the select value, and in the case (a) the triggers will work. However, the second case will not be detected.

How can I make the binding, so it will detect the case (b) too.

Upvotes: 1

Views: 72

Answers (2)

dfsq
dfsq

Reputation: 193261

Method $.fn.val doesn't trigger change event itself. The simplest thing you can do is to trigger it manually when you need it. If however you really want it to happen automatically you can extend valHook setter of the select element:

$.valHooks.select.set = function(orig) {
    return function(el) {
        var result = orig.apply(this, arguments);
        $(el).trigger('change');
        return result;
    };
}($.valHooks.select.set);

This seems to work fine. You just take original hook and complement it with triggering code.

Demo: http://jsfiddle.net/cq07fL29/

Upvotes: 2

nanndoj
nanndoj

Reputation: 6770

Try using .trigger():

jQuery('#selectId').val("2").trigger("change");

EDIT: Following the tip from @Rory McCrossan you can extend the val() function to trigger the event if it's a select element

  // Save old val
  var oldVal = $.fn.val;
  $.fn.val = function(value) {
      // Execute parent val() 
      obj = oldVal.apply(this, arguments);

      // If it is a select
      if(Object.prototype.toString.apply(this.get(0)) == '[object HTMLSelectElement]') {
          // Trigger the event
          this.trigger("change");
      }
      return obj;
  };

  $(document).ready(function() {
    jQuery('#selectId').val("v3");
  });

here is a working FIDDLE

Upvotes: 0

Related Questions