Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 = "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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading