MavrosGatos MavrosGatos - 6 months ago 36
jQuery Question

Backbone click event not firing in Google Chrome

I have the following code and it works in every browser except Google Chrome.
I want every time I click on an option to alert me with the "You selected option (selected option number)" text.
I cannot make it work.

var MyView = Backbone.View.extend({

el : "#eventPage",

initialize : function(options) {
_.bindAll(this, 'render', 'changeNum');
this.render();
},

render : function(){
var a = [];
var b = 0;

a[b++] = '<div>';
a[b++] = ' <select id="select">';
a[b++] = ' <option class="sel" id="1">ONE</option>';
a[b++] = ' <option class="sel" id="2">TWO</option>';
a[b++] = ' <option class="sel" id="3">THREE</option>';
a[b++] = ' </select>';
a[b++] = '</div>';

$(this.el).html(a.join(""));
},

events : {
"click #select .sel":"changeNum"
},

changeNum : function(e){
alert("You selected option "+$(e.currentTarget).attr("id"))
}
});

Answer

Rather than listening for click on your option elements, you should listen for change on your select element:

events: {
    "change #select":"changeNum"
}

Then in your changeNum function you can get the selected option:

changeNum: function(e) {
    alert("You selected option "+$(e.currentTarget).find('option:selected').attr('id'));
}

Here is a working fiddle: https://jsfiddle.net/vt7t47br/