Skip to content Skip to sidebar Skip to footer

Event Attached To Option Node Not Being Fired

I have this code var option = new Option(thatOption.text, thatOption.value); $(option).click( function(){ //Sorry cannot reveal what is here I'll just use t

Solution 1:

Why does that happen?

The root cause of this has been discussed a few times already on SO:

Older versions of IE simply don't support click events on <option> elements. Instead, you'll have to listen to the <select>'s change (or click) event:

$(selectBox).change(function () {
});

Regarding your specific task, to have the alert appear (or your actual code execute) only when that option is selected, you can test if the option is selected within the change event:

var option = newOption(thatOption.text, thatOption.value);

$(selectBox).change(function () {
    if ($(option).is(':selected')) {
        alert('clicked');
    }
});

If you don't have the option variable at the ready, you can instead test with the value of the <select>:

$(selectBox).change(function () {
    if ($(this).val() === 'something') {
        alert();
    }
});

Also, to avoid the try..catch and Stupid IE doesn't know how to follow the spec, you can do just:

$(selectBox).append(option);

Post a Comment for "Event Attached To Option Node Not Being Fired"