What I do here is that I dynamically create a drop-down and bind the click
event to the <option>
within the <select>
var $select = $('<select></select>'),
$option1 = $('<option>a</option>'),
$option2 = $('<option>b</option>');
$option1.val(1);
$option2.val(2);
$(document.body).on('click','select option',function(){
console.log("click-option works");
});
$select.append($option1);
$select.append($option2);
$(document.body).append($select);
As I read here, Since I am dynamically adding content, I delegated the event handling to the top most element in the DOM.
Now my problem is this is not working in chrome as expected. In fire-fox it seems to work fine.
I have also read through this link and the other one but to no avail.
Interestingly when I do this in the place of 'select option'
selector
$(document.body).on('click','select',function(){
console.log("click-option works");
});
The output is logged, However that is definitely not what I had in mind. The output is logged whenever I select the drop-down itself, not to mention the options in the drop-down. As a temporary work around I am using change
event in the following way :
$(document.body).on('change','select',function(event){
console.log("change works");
console.log(event);
});
This seems to do the trick,However I want to know why It is not working in the original case and any work-arounds if possible.
Here is a fiddle for what I have done so far.
UPDATE : I have also checked out this link. However that is for just pure javascript, I wanted to know why it snot working in my case. More specifically, in the delegated event handler where we specifiy the selector, Why does it fail at 'select option'
and work at 'select'
in chrome ?