Reputation: 12512
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?
Upvotes: 1
Views: 35
Reputation: 31987
append
inserts the DOMString
s 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;
}
})();
Upvotes: 3
Reputation: 137
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);
Upvotes: 0