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

88
Visualizações
Remove options before appending new ones

I'm writing a function in plain Javascript where I submit some values via AJAX and if it returns results I need to remove all options from a selector and replace them with the set that's returned.

HTML

<select id="mySelector">
....

JS

(async () => {
    ....
    const res = await fetch(url, {
        method: "POST",
        headers,
        body
    });

    if (results.ok) {                                
        let myoptions = await results.text();
        var myselectr = document.querySelector("#mySelector");
        myselectr.options.length = 0;                    
        myselectr.append(myoptions);
    }
})();

It seems that it does remove earlier options but only on the fist change. All subsequent attempts just keep adding new sets of options.

What am I missing here?

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

0

You can do like this

(async () => {
....
const res = await fetch(url, {
    method: "POST",
    headers,
    body
});

if (results.ok) {                                
    let myoptions = await results.text();
    var myselectr = document.querySelector("#mySelector");
    myselectr.innerHTML = ""; // Updated             
    myselectr.append(myoptions);
}
})();
about 4 years ago · Juan Pablo Isaza Relatório

0

you should keep currentOptions in memory (not on ui). When you have extra options, you append to currentOptions then render the UI selection with currentOptions again.

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