Home > Mobile >  Returned options are not seem by selector
Returned options are not seem by selector

Time:10-14

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

HTML

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

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.innerHTML = "";                     
        myselectr.append(myoptions);
    }
})();

It seems to return options and I see them added in DOM but the selector does not seem to see them as options. The thing is I actually need to build the options using my PHP functionality. I think it is because I return it as text string. Not really sure.

What am I missing here?

CodePudding user response:

append inserts the DOMStrings as Text nodes, causing HTML to be escaped. You should be assigning myoptions to the select's innerHTML instead:

(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 = myoptions;                     

    }
})();

CodePudding user response:

What is the return format after you made the request is it a array.. if its a array then append options manually using a for loop.

var myselectr = document.querySelector("#mySelector");
var option = document.createElement("option");
option.text = "Text";
option.value = "myvalue";
myselectr.append(option);
  • Related