skip to Main Content

enter image description hereHere’s what I have so far

main.html (it’s a form btw)

 <div class="form-group form-check-inline">
     <input class="form-check-input" type="radio" name="region" id="US" value="US">
     <label class="form-check-label" for="US">US</label>
</div>

api.js

document.addEventListener('DOMContentLoaded', () => {
const urlUS = new URL("http://127.0.0.1:3000/api/v1/regionApi/regionProduct/1")
document.getElementById('US').addEventListener('click', getRegionUS)

function getRegionUS() {
        fetch(urlUS, {
            method:'GET'
        })
            .then(res => res.json())
            .then(data => {
                data.forEach(function(product){
                    output = `
                    <div class="form-group form-check">
                    <input class="form-check-input" type="checkbox" value="${product.productname}" id="${product.id}">
                    <label class="form-check-label" for="${product.id}">
                    ${product.productname}
                    </label>
                    </div>
                    `
                })
                
                document.getElementById('US').innerHTML = output
                console.log(data)
            })
            .catch(error => console.log('error'))
    }

})

When clicking on the radio button I do get the information I am looking for in my api. What am I missing ? Why wouldn’t it appear in checkboxes ? What should I try ?

2

Answers


  1. You appear to have a couple of issues with your code…

    1. You’re replacing the HTML outside the foreach but it only ever uses the last assignment to output as it is overwritten each iteration.
    2. You’re attempting to add the HTML inside a checkbox input element which is not allowed.

    You will need to build up the HTML, adding to it each iteration, before inserting it all in to the page afterwards. You will also need somewhere else on the page to add the generated HTML. See below

    Please Note: I have used a freely available JSON API designed for supplying fake test data so I’ve had to change the HTML generation slightly to work with that data

    document.addEventListener('DOMContentLoaded', () => {
      const urlUS = new URL("https://jsonplaceholder.typicode.com/users")
      document.getElementById('US').addEventListener('click', getRegionUS)
    
      function getRegionUS() {
        fetch(urlUS, { method: 'GET' })
          .then(res => res.json())
          .then(data => {
            let output = '';
    
            data.forEach(function(product) {
              output += `
                        <div class="form-group form-check">
                        <input class="form-check-input" type="checkbox" value="${product.name}" id="${product.id}">
                        <label class="form-check-label" for="${product.id}">
                        ${product.name}
                        </label>
                        </div>
                        `;
            })
    
            document.getElementById('productInfo').innerHTML = output;
            // console.log(data)
          })
          .catch(error => console.log('error'))
      }
    })
    <div class="form-group form-check-inline">
      <input class="form-check-input" type="radio" name="region" id="US" value="US">
      <label class="form-check-label" for="US">US</label>
    </div>
    
    <div id="productInfo">Generated HTML will appear here!</div>
    Login or Signup to reply.
  2. This can be more elegant and DRY – I delegate from a container here

    Note I reused the JSON mock data url from the other answer.
    Change the product.whatever to match your object

    const regions = {
      "US": 1,
      "EUR": 2
    };
    const url = 'https://jsonplaceholder.typicode.com/posts?userId=';
    
    document.addEventListener('DOMContentLoaded', () => {
      document.getElementById('item-carousel').addEventListener('click', (e) => {
        const tgt = e.target;
        fetch(`${url}${regions[tgt.id]}`, { method: 'GET' })
          .then(res => res.json())
          .then(data => {
            document.getElementById('productInfo').innerHTML = data.map(product => `<div class="form-group form-check">
                        <input class="form-check-input" type="checkbox" value="${product.title}" id="${product.id}">
                        <label class="form-check-label" for="${product.id}">${product.body}</label>
                        </div>`).join('');
          });
      });
    });
    <div id="item-carousel">
      <div class="form-group form-check-inline">
        <input class="form-check-input" type="radio" name="region" id="US" value="US">
        <label class="form-check-label" for="US">US</label>
      </div>
      <div class="form-group form-check-inline">
        <input class="form-check-input" type="radio" name="region" id="EUR" value="EUR">
        <label class="form-check-label" for="EUR">EUR</label>
      </div>
    </div>
    <div id="productInfo">Generated HTML will appear here!</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search