Billy Shih
Billy Shih

Reputation: 624

Backbone change event not fired for select field selected by jQuery

I have a button that when clicked sets the value of a select field and also have a change event for the select field. The 'change select[name=location_id]' event works when selecting normally via mouse/keyboard but clicking the button, which uses jQuery to change the select field value, doesn't fire off the 'change select[name=location_id]' event.

How do I get the 'change select[name=location_id]' to fire when changing the field via jQuery?

SubscriptionsModule.Views.SubscriptionEditView = Backbone.Marionette.LayoutView.extend({
    template: "subscriptions/edit",
    events: {
      'click #home-delivery-select': 'selectHomeDeliverySite',
      'change select[name=location_id]': 'updateLocation'
    },
    selectHomeDeliverySite: function() {
      this.$el.find('select[name=location_id]').val(this.model.get('hd_location_id'));
    },
    updateLocation: function(e) {
      //update location code
    },
    updateOrderSize: function(e) {
      SubscriptionsModule.eventManager.trigger('updateOrderSize', $(e.currentTarget).data('price'));
    }
  });

Upvotes: 3

Views: 2927

Answers (3)

seebiscuit
seebiscuit

Reputation: 5053

Update

Also, please disregard the below answer, since as per the MDN input event docs, the input event only fires for <input> and <textarea> and will not fire for <select>, since the value of <select> doesn't change when any of its options are selected (btw, <input> with type checkbox or radio will also not emit an input event since their value attribute is not changed on selection(!).

I'll leave the answer up for reference.


The following is incorrect

From the MDN

The change event is fired for <input>, <select>, and <textarea> elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.

According to Quirksmode, the change event is buggy for all IE and Opera.

Try replacing

'change select[name=location_id]': 'updateLocation'

with

'input select[name=location_id]': 'updateLocation'

Upvotes: 2

Steven Barrag&#225;n
Steven Barrag&#225;n

Reputation: 1244

To trigger the change event on backbone after you change something with jquery you need to trigger the change event.

elem.trigger('change')

http://api.jquery.com/trigger/

Upvotes: 0

u.k
u.k

Reputation: 3091

All you need is to add an event:

this.$('select[name=location_id]').val(this.model.get('hd_location_id')).trigger('change');

Upvotes: 1

Related Questions