skip to Main Content

I have a static portfolio website without database, I want to count no. of products on one page and display it on another one .

Right now I have come up with this

<script>
    const elements = document.querySelectorAll('.product');
    const count = elements.length;
    document.getElementById("Count_exec_chair").innerHTML = count;
</script>

But This only works within same page . I want to count products on 3 different pages and display them on 4th one.

(Context : It’s a small furniture company’s website , they have added 15-20 Products of 4 categories Manually in Divs using

and

Now They want me to make code so that whenever someone add product the count in menu increases .)

2

Answers


  1. In the OP it isn’t certain how a user selects a <div> and how to keep track of said <div> so the example I’ve provided uses <input type="checkbox"> as a means for the user to select an item.

    // All of a <form>'s <fieldset>, <input>, and <output> into an array
    const items = Array.from(document.forms[0].elements);
    // Iterating through the array, return the index of selected items or nothing
    const cnt = items.flatMap((item, index) => item.checked ? index : [])
    

    Each page has a <fieldset> – (document.forms[0].elements[0]), and four <input type="checkbox"> – (document.forms[0].elements[1 - 4]), and the last page has an <output> – (document.forms[0].elements[5]) as well.

    Each page has a number value assigned to variable idx 0 to 3. Each page is also represented as an object literal: {} stored within an array that’s stored as a string within localStorage. Each object literal has two properties:

    {
      selected: [1, 2, 3, 4] // index numbers of selected `<input>`
      total: 4 // total of selected `<input>`
    }
    

    Any time a page is loaded the array of objects is retrieved from localStorage and the <input>s are checked according to the object’s .selected property (ex. [2, 3] <input> 2 and 3 are checked). Anytime an <input> is checked (or unchecked) the corresponding index of that <input> is added to that page’s object .selected array.

    In addition, the last page’s <output> will display the total sum of each object’s total property every time it’s loaded or if a user selects (or deslects) an <input>.

    localStorage does not function in a SO Snippet so go here for a working example.

    const key = 'count';
    
    function getCount(key) {
      return JSON.parse(localStorage.getItem(key)) || [{}, {}, {}, {}];
    }
    
    function getSelected() {
      const items = Array.from(document.forms[0].elements);
      return items.flatMap((item, index) => (item.checked ? index : []));
    }
    
    function setSelected() {
      const items = Array.from(document.forms[0].elements);
      const counts = getCount(key);
      counts[idx].selected.forEach((number) => (items[number].checked = true));
    }
    
    function addSelected() {
      const counts = getCount(key);
      const cnt = getSelected();
      counts[idx].selected = cnt;
      counts[idx].total = cnt.length;
      localStorage.setItem(key, JSON.stringify(counts));
    }
    
    function totalSelected() {
      const counts = getCount(key);
      const total = counts.reduce((sum, page) => sum + page.total, 0);
      document.forms[0].elements.grandTotal.value = total;
    }
    
    document.addEventListener('DOMContentLoaded', setSelected);
    document.forms[0].addEventListener('change', addSelected);
    :root {
      font: 5vmin/1 'Segoe UI';
    }
    menu {
      list-style: none;
      padding: 0;
      display: flex;
      justify-content: space-evenly;
    }
    label {
      display: flex;
      align-items: center;
      margin-bottom: 0.5rem;
    }
    [type='checkbox'] {
      width: 1rem;
      height: 1rem;
      margin-left: 0.5rem;
    }
    <!DOCTYPE html>
    
    <html>
      <head>
        <link rel="stylesheet" href="lib/style.css" />
      </head>
    
      <body>
        <nav>
          <menu>
            <li><a href="index.html">Page 1</a></li>
            <li><a href="page2.html">Page 2</a></li>
            <li><a href="page3.html">Page 3</a></li>
            <li><a>Page 4</a></li>
          </menu>
        </nav>
        <form>
          <fieldset>
            <label> Item 13 <input type="checkbox" /> </label>
            <label> Item 14 <input type="checkbox" /> </label>
            <label> Item 15 <input type="checkbox" /> </label>
            <label> Item 16 <input type="checkbox" /> </label>
            <label> Total: &nbsp;&nbsp;<output id="grandTotal"></output> </label>
          </fieldset>
        </form>
        <script>
          const idx = 3;
        </script>
        <script src="lib/script.js"></script>
        <script>
          document.addEventListener('DOMContentLoaded', totalSelected);
          document.forms[0].addEventListener('change', totalSelected);
        </script>
      </body>
    </html>
    Login or Signup to reply.
  2. If you don’t have access to a database or server, you may be able to use fetch(). For instance, if you put this in the console of this page, it should show how many elements have the -link--channel-name class on the Stack Overflow question page:

    Note: Please be careful when copying and pasting code into the console. Make sure you are aware of what each line of code does.

    fetch('https://stackoverflow.com/')
     .then(result => result.text())
     .then(text => {
      var match = text.match(/class=["'][^"']*-link--channel-name[^"']*["']/g);
      if(match) console.log(`Matches found: ${match.length}`);
      else console.log(`Matches found: 0`);
    });
    

    I would provide a snippet, but fetch can be tricky. When attempting to use a snippet, the Stack Overflow CORS policy stopped it from working.

    I should also mention that fetch will only work for you if the page you’re trying to access has the class written in the HTML. This method cannot detect a class or elements that are added after the page loads. In this instance, if I search for the s-link class (links to questions) I get no matches.

    If fetch does work for your website, here is what that code does:

    // Send a fetch request to the disired url.
    // If on your own domain, you might not have to use a full url.
    fetch('https://stackoverflow.com/')
    
     // Take the result of that request and retrieve the text from it (the HTML of the page).
     .then(result => result.text())
    
     .then(text => {
      // Take the text and search for the class using a regular expression.
      var match = text.match(/class=["'][^"']*-link--channel-name[^"']*["']/g);
    
      // Do something with the result.
      if(match) console.log(`Matches found: ${match.length}`);
      else console.log(`Matches found: 0`);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search