Save and showcase an array as individual objects within local storage

I am looking to input data using a specific product ID and save it locally. Upon clicking the button, the data should be stored in the local storage. It is possible for a single product to have multiple filenames associated with it.

For the customer, if they provide the ID, all the filenames linked to that ID should be displayed in a text area.

 <!DOCTYPE html>
    <html>
        <title>W3.CSS</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
            <script type="text/javascript">
                var filename = []
            var productid = []

            function managerClick(){
                console.log("manager", productid);  
                console.log("manager", filename);   

                productid.push(document.getElementById("productId").value);
                filename.push(document.getElementById("names").value);

                localStorage.setItem("filename", JSON.stringify(filename)); 
                localStorage.setItem("productid", JSON.stringify(productid));   

                var result={}
                   productid.map(function(k){
                   result[k]=filename;
                   })
                  console.log(result);         

                console.log("productid",productid); 
                console.log("filename",filename);       
            };
                function customerClick(){
                  console.log("Customer");
                 document.getElementById('myTextarea').value = filename;

             };
            </script>
        <body>
            <div class="w3-card-4 w3-margin" style="width:50%;">         
                 <center>Product Manager</center>

                <div class="w3-container">
                    Product ID: <input type="text" id="productId"><br></br>
                    File Name: <input type="text" id="names"><br></br>
                    <center><button class="w3-btn w3-dark-grey" onclick="managerClick()">Enter Data</button></center><br>
                </div>

                 <center>Customer Section</center>

                <div class="w3-container">
                    Product ID: <input type="text" id="CustomerpId"><br></br>               
                    <center>
                        <button class="w3-btn w3-dark-grey" onclick="customerClick()">Click To Get Filenames</button>
                    </center><br>
                    <textarea rows="4" cols="30"></textarea>
                </div>
            </div>
        </body>
    </html> 

I am looking to assign multiple files to a single product without them being visible to other products. Can someone assist me in achieving this?

I tried implementing the solution mentioned above and encountered issues.

https://i.sstatic.net/j0emN.png

Despite following the instructions, the filenames of product 1 and product 2 are displayed for both products. Ideally, product 1 should have files 1, 2, and 3, while product 2 should have files 1, 2, 3, and 4

Answer №1

give this a go

<script type="text/javascript">

    var productList = []

    function manageProducts() {

        productList.push({ productid: document.getElementById("productId").value, filename: document.getElementById("names").value });

        localStorage.setItem("ProductList", JSON.stringify(productList));

    };
    
    function selectProduct() {

        var products = JSON.parse(localStorage.getItem("ProductList"));
        var selectedProductId = document.getElementById("CustomerpId").value;

        for (var i = 0; i < products.length; i++) {
            if (products[i].productid == selectedProductId) {
                document.getElementById('myTextarea').value = document.getElementById('myTextarea').value + " " + products[i].filename;

                console.log(products[i].filename);
            }
        }
    };
</script>

<textarea rows="4" cols="30" id="myTextarea"></textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The component briefly displays the previous state before updating in the Material-UI Alert component

Whenever there is an error from an API while a user is registering, an alert is displayed on the form page. To handle this, an Alert component was created: <Snackbar open={open} autoHideDuration={9000} onClose={() => { setOpen(f ...

Can ng-packagr create scripts that are compatible with running in a web browser like regular JavaScript?

Is it feasible to utilize ng-packagr to compile a library into a single script file that can be executed on a web browser by importing it as <script src="bundle.js"></script>? For instance, if I have a main.ts file that contains cons ...

Searching the JSON file by its value using Waterline

I am struggling with locating model instances based on the nested address attribute in one of my models. attributes: { address: { type: 'json' } } I have attempted various queries to find model instances located in the same city: Model ...

Custom properties of an object are being erased when converting to JSON format within the canvas

I am working on a canvas project that involves multiple image objects, each with custom attributes. My goal is to save this canvas as a json object in a database, but the conversion process seems to strip away the custom attributes. Currently, I am using t ...

Using GraphQL to set default values in data within a useEffect hook can lead to never

Here's the code snippet that I'm working with: const [localState, setLocalState] = useState<StateType[]>([]); const { data = { attribute: [] }, loading } = useQuery<DataType>(QUERY, { variables: { id: client && client.id ...

Can we expect Karma to receive updates for upcoming versions of Angular and Jasmine?

We recently attempted to upgrade our company's Angular module, which required updating dependencies as well. Upon upgrading to the latest versions, we encountered an issue with the Jasmine-karma-HTML-Reporter due to its reliance on Jasmine-core 4.x.x ...

Accessing the media player of your system while developing a VSCode extension using a nodejs backend: A comprehensive guide

I am currently utilizing the play-sound library in my project. I have experimented with two different code snippets, each resulting in a unique outcome, none of which are successful. When I implement const player = require('play-sound')({player: ...

Utilizing ID for Data Filtering

[ { "acronym": "VMF", "defaultValue": "Video & Audio Management Function", "description": "This is defined as the Video and/or Audio Management functionality that can be performed on a Digital Item. The Video & Audio M ...

Two selection options controlling filters. The first choice influences the data shown in the second filter

I've been struggling for hours to figure out how to build this functionality. My code seems to be getting close, but I'm having trouble passing my selection from the HTML back to the controller. Here's my Angular code: var Categories = Pa ...

How to refresh an image in Next.js using setState even when the src path remains unchanged

Define a state variable: const [picture, setPicture] = useState(null); Assuming the picture is initially set to "123" and even after updating the image, the value remains "123". How can I reload the Image? <Image src={profileurl + picture} alt="profile ...

What are some other options for pushing out data instead of using window.onbeforeunload?

I have an AJAX function that interacts with my PHP script. The purpose was to delete empty MySQL entries when the user closes the page. Initially, I thought window.onbeforeunload would be ideal for this task, but it seems in the latest version of Chrome i ...

Transforming a string into an array containing objects

Can you help me understand how to transform a string into an array of objects? let str = `<%-found%>`; let result = []; JSON.parse(`["${str}"]`.replace(/},{/g, `}","{`)).forEach((e) => ...

What should be done if an image is not wide enough to stretch it to match the width of the window?

When the image is not full screen, it looks fine but when it's viewed in full screen, there's a white area on the right side which is likely due to the image not being large enough. Is there a way to automatically stretch the image so that its wi ...

Tips for styling the selected or clicked cell of an HTML5 table

Currently, I am working on a web development project to enhance my skills. I am looking to incorporate a feature that changes the color of a clicked cell to a specific color. For a demonstration, you can view this link: https://jsfiddle.net/pz6tc3ae/30/ T ...

Enumeration field with Conditional logic

I am currently developing a Content Management System (CMS) using strapi for a client, and I want to provide them with the ability to control the questions included in a questionnaire. Each question will be categorized under different sections in the quest ...

A superior method for implementing CSS keyframe transitions

Currently, I am utilizing the Rico St.Cruz brilliant query.transit library for my work. However, I need to make some changes involving classes instead of CSS transitions. Although I am not very confident in CSS transitions, I attempted to replace: JS: $ ...

``What methods can I use to split JSON data using logstash and visualize it in Kibana?

I am facing an issue with parsing a log file containing multiple lines of JSON data. One line from the log looks like this: {"name":"sampleApplicationName","hostname":"sampleHostName","pid":000000,"AppModule":"sampleAppModuleName","msg":"testMessage","tim ...

Unable to serialize stream data in ASP .NET Core

Attempting to deserialize objects from an HTTP response. The response stream contains JSON information, which has been verified as valid through an online deserializer. I obtained the object class from the API framework, so I believe all properties should ...

Displaying a Google chart with no data using JSON

Recently, I've been tackling the challenge of setting up Google Charts to display data from a local database. After some persistence, I believe I have successfully formatted the JSON output. { "cols": [ { "id": "", ...

Exchange the draggable elements between distinct div containers while keeping them in their original positions

Attempting to create an example showcasing Draggable jQuery with Bootstrap, everything is functioning smoothly so far. However, there are two things I am aiming to achieve: Swap the divs <div class='col-sm-12'></div> that were gen ...