I’m trying to dynamically set options for a <select>. When setting the label for <outgroup>, the string is being broken before the phrase completes. Ex HTML output: <optgroup label="Computers," electronics,="" & internet="" technology=""></optgroup>
It;s supposed to be "Computers, Electronics, &Â Internet technology"
let select = document.querySelector("#category");
const categoriesURL = "https://x5ab-h0sq-ptse.n7.xano.io/api:R5KpHaH2/categories";
let str = "";
fetch(categoriesURL)
.then(response => response.json())
.then(data => {
data.forEach(category => {
let categoryTitle = category.title;
str += `<optgroup label=${categoryTitle}></optgroup>`
category.subcategories.forEach(sub => {
let subcategories_id = sub.subcategories_id;
let subcategoriesURL = `https://x5ab-h0sq-ptse.n7.xano.io/api:R5KpHaH2/subcategories/${subcategories_id}`;
fetch(subcategoriesURL)
.then(response => response.json())
.then(subData => {
str += `<option value=${sub.subcategories_id}>` + subData.title + "</option>";
})
})
})
select.innerHTML = "<option disabled selected>Select a category</option>" + str;
});
Also, my subcategories aren’t populating… Don’t know what’s wrong here.
>Solution :
Try label="${categoryTitle}" with quotes, because without quotes, it will generate
<optgroup label=Computers, Electronics, & Internet technology>
which is invalid, so the browser adds quotes around each word, and thinks Electronics is another attribute, leading to your problem.