Neta Meta
Neta Meta

Reputation: 4047

Is it possible to bind select option On select and not On change

i am trying to bind an event when user selected an item from <select> not necessary changed from the default.

$(select).change(); only works if the item was changed.

i wonder if there is something that works by selecting one of the options even if its the same default option.

$('#page_body').on('select', '.pop_pin_select', function() {
});

This is what i try so far but it wont work.

Upvotes: 4

Views: 3089

Answers (1)

Paul S.
Paul S.

Reputation: 66324

There is a way around this; making the option at index 0 the default selected, dynamic and not manually selectable (i.e. disabled) and listen for onchange as normal, except when changing to index 0. Then onchange, set .options[0] to chosen label and value and change selection to it. Here is an example.

Relevant JavaScript from example

document.getElementById('sel')
    .addEventListener('change', function () {
        if (this.selectedIndex === 0) return;
        this.options[0].value = this.value;
        this.options[0].textContent = this.options[this.selectedIndex].textContent;
        this.selectedIndex = 0;
    }, false);​

onchange will fire when a user makes the same selection because the index is changing even though the value isn't.

Upvotes: 1

Related Questions