2

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?

santa
  • 12,234
  • 49
  • 155
  • 255
  • 1
    Does this answer your question? [Remove all child elements of a DOM node in JavaScript](https://stackoverflow.com/questions/3955229/remove-all-child-elements-of-a-dom-node-in-javascript) –  Oct 13 '21 at 23:12
  • @Spectric It appends just fine. The problem I have - it does not clear options before appending. It does it only once, the first time. – santa Oct 13 '21 at 23:12

2 Answers2

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);
}
})();
maca
  • 480
  • 3
  • 12
-1

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.