Search code examples
javascripthtml-selecttemplate-literalsoptgroup

Comma in variable breaks template literal output


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,="" &&nbsp;internet="" technology=""></optgroup>

It;s supposed to be "Computers, Electronics, & Internet technology"

let select = document.querySelector("#category");
const categoriesURL = "INSERT_URL";
  
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 = `INSERT_URL/${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.