简体   繁体   中英

Get innertext from joined array of JSON onclick using javascript

I am a newbie trying to build a shopping cart app. I found a very nice demo online and I am trying to tweek it to use for my own purposes. The app includes and autocomplete input that will fetch all the json elements inside.json file. That part works great. However, once the json is fetched it is joined together based on the search criteria. Again, this is desired. However, what i want to happen next is for the user to click one of the products in the list and that product get added to the html table. Can anyone recommend how I should do this?

 const search = document.getElementById('search'); const matchList = document.getElementById('match-list'); //let states; // Get products const getPricelist = async() => { const res = await fetch('pricelist.json'); pricelist = await res.json(); }; // Filter products const searchPricelist = (searchText) => { // Get matches to current text input let matches = pricelist.filter((pricelist) => { const regex = new RegExp(`^${searchText}`, 'gi'); return ( pricelist.product.match(regex) || pricelist.product_category.match(regex) || pricelist.product_class.match(regex) || pricelist.partnumber.match(regex) || pricelist.product_abbr.match(regex) || pricelist.product_type.match(regex) ); }); // Clear when input or matches are empty if (searchText.length === 0) { matches = []; matchList.innerHTML = ''; } outputHtml(matches); }; // Show results in HTML const outputHtml = (matches) => { if (matches.length > 0) { const html = matches.map( (match) => `<div id="test" onclick="myFunction()" class="product-card card card-body mb-1"><h4>${match.product} <br><strong> ${match.product_category} (${match.product_class})</strong></h4> <small>Part Number: <strong>${match.partnumber}</strong> <br>List Price: <strong>${match.list}</strong></small> <small>Description: <strong>${match.description}</strong></small> </div>`).join(''); matchList.innerHTML = html; } }; window.addEventListener('DOMContentLoaded', getPricelist); search.addEventListener('input', () => searchPricelist(search.value)); function myFunction(event) { window.onclick = (e) => { console.log(e.target.innerText); } search.value = ""; matches = []; matchList.innerHTML = ''; };
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1:0" /> <link rel="stylesheet" href="https.//bootswatch.com/4/flatly/bootstrap.min.css" /> <title>Autocomplete</title> </head> <body> <div class="container mt-5"> <div class="row"> <div class="col-md-6 m-auto"> <h3 class="text-center mb-3"> Autocomplete </h3> <div class="form-group"> <input type="text" id="search" class="form-control form-control-lg" placeholder="Enter Product Name or Abbreviation" /> </div> <div id="match-list"></div> <br /> <h3 class="text-center mb-3"> Shopping Cart </h3> <div> <table class="table table-striped mt-5"> <thead> <tr> <th>Part Number</th> <th>List Price</th> <th>Product</th> <th>Product Category</th> <th>Description</th> </tr> </thead> <tbody id="shopping-cart"></tbody> </table> </div> </div> </div> </div> <script src="main.js"></script> </body> </html>

                [
                {
                    "partnumber": "1",
                    "list": "$100.00 ",
                    "product": "Ford",
                    "product_type": "Mustang",
                    "product_category": "Sports Car",
                    "product_class": "GTE",
                    "product_abbr": "Mustang",
                    "description": "Ford Mustang GTE Sports Car"
                },
                {
                    "partnumber": "2",
                    "list": "$200.00 ",
                    "product": "Ford",
                    "product_type": "Bronco",
                    "product_category": "SUV",
                    "product_class": "Truck",
                    "product_abbr": "Bronco",
                    "description": "Ford Bronco SUV Truck"
                },
            ]

The js portion should look like this, tested and verified it looks to work.

const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
//let states;

// Get products
const getPricelist = async() => {
  const res = await fetch('pricelist.json');
  pricelist = await res.json();
};

// Filter products
const searchPricelist = (searchText) => {
  // Get matches to current text input
  let matches = pricelist.filter((pricelist) => {
    const regex = new RegExp(`^${searchText}`, 'gi');
    return (
      pricelist.product.match(regex) ||
      pricelist.product_category.match(regex) ||
      pricelist.product_class.match(regex) ||
      pricelist.partnumber.match(regex) ||
      pricelist.product_abbr.match(regex) ||
      pricelist.product_type.match(regex)
    );
  });

  // Clear when input or matches are empty
  if (searchText.length === 0) {
    matches = [];
    matchList.innerHTML = '';
  }

  outputHtml(matches);
};
// Show results in HTML
const outputHtml = (matches) => {
  if (matches.length > 0) {
    const html = matches

      .map(
        (match) =>
        `<div id="${match.partnumber}" class="product-card card card-body mb-1"><h4>${match.product}
                    <br><strong> ${match.product_category} (${match.product_class})</strong></h4>
                    <small>Part Number: <strong>${match.partnumber}</strong>
                    <br>List Price: <strong>${match.list}</strong></small>
                    <small>Description: <strong>${match.description}</strong></small>
                    </div>`
                    )
      .join('');
    matchList.innerHTML = html;
    $('.product-card').click(myFunction)
  }
};


window.addEventListener('DOMContentLoaded', getPricelist);
search.addEventListener('input', () => searchPricelist(search.value));

function myFunction() {

  const id = $(this).attr('id')
  const product = pricelist.filter(prod => prod.partnumber === id)[0]
  if(product){
    $('.table').append(`
        <tr>
          <th>${product.partnumber}</th>
          <th>${product.list}</th>
          <th>${product.product}</th>
          <th>${product.product_category}</th>
          <th>${product.description}</th>
        </tr>
    `)
  }
  search.value = "";
  matches = [];
  matchList.innerHTML = '';

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM