Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Is it possible to listen for selectedIndex change?

I am looking for a way (or a workaround) to subscribe for selectedIndex changing (on <select> element) when the change done by a simple assignment (like myElement.selectedIndex=1).

<select id = "mySelect" onchange="myListener()">
    <option>0</option>
    <option>1</option>
</select>

<script>
    function myListener() {
        console.log('Yes, I hear...'); // doesn't work on selectedIndex assignment
    }
    document.getElementById('mySelect').selectedIndex = 1;
</script>

Seems it's not possible, but maybe there is some workaround.
dispatchEvent is not an option (the listener attachment must be done from outside).


My only solution so far, very similar to @jren510 (but I like his solution more).

function myListener() {
    console.log('Yes, I hear...');
}

const originalPropDescriptor = Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, 'selectedIndex');

Object.defineProperty(HTMLSelectElement.prototype, 'originalSelectedIndex', originalPropDescriptor);

Object.defineProperty(HTMLSelectElement.prototype, 'selectedIndex', {
    get() {
        return this.originalSelectedIndex;
    },

    set(value) {
        myListener();
        this.originalSelectedIndex = value;
    }
});

I would like to avoid overriding native methods, by so far it's the only way I see.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Maybe not the best answer, but you did mention workarounds..

You can try overriding the setter for the object for which you are trying to detect the change in.

let mySelect = document.getElementById("mySelect");

const callback = () => {
    console.log("Yes, I hear...");
};

const original = Object.getOwnPropertyDescriptor(
    Object.getPrototypeOf(mySelect),
    "selectedIndex"
);
Object.defineProperty(mySelect, "selectedIndex", {
    set: function (t) {
        callback();
        return original.set.apply(this, arguments);
    },
    get: function () {
        return original.get.apply(this);
    }
});

let myButton = document.getElementById("myButton");
myButton.addEventListener("click", () => {
    mySelect.selectedIndex = 1;
});
<select id="mySelect">
    <option>0</option>
    <option>1</option>
</select>

<button id="myButton"> change selector value to 1 </button>

It's worth mentioning that the callback does not run when manually changing the select here.. if you want to preserve that behavior, you can add an event listener that calls callback as usual, though there may exist a better solution that captures both cases.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda