Home > Blockchain >  Remove options before appending new ones
Remove options before appending new ones

Time:10-14

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?

CodePudding user response:

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);
}
})();

CodePudding user response:

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.

  • Related