Using a local JSON file's key as a variable within a JavaScript function: a step-by-step guide

I am working on a small system to track sales. The goal is to have the ability to click on a specific item, and both the total value (items sold) and revenue increase accordingly.

Currently, I have a button with a JavaScript function called incrementValueAndRevenue() which is functioning correctly. However, I am only able to make it work by declaring JSON within the function itself. I would ideally like it to dynamically calculate the total price for each item in my local JSON file based on how many of that specific item has been clicked.

It's worth mentioning that this is being done using Razor Pages.

Below is a snippet of my JSON data:

[
  {
    "Id": 1,
    "Image": "exorcist.jpg",
    "Name": "EXORCIST",
    "Price": 20.00
  },
  {
    "Id": 2,
    "Image": "hoodie.jpg",
    "Name": "LOGO HOODIE",
    "Price": 30.00
  },
  {
    "Id": 3,
    "Image": "dadhat.jpg",
    "Name": "DAD HAT",
    "Price": 25.00
  }
]

Here is the relevant HTML code:

<div class="merch-container">
            <ul class="merch-ul">
                @foreach (var item in Model.Items)
                {
                    <li class="merch-display">
                        <img src="~/imgs/@item.Image" style="width: 250px; height: 250px; padding: 15px; object-fit: cover;" />
                        <p id="item-price">@item.Price</p>
                        <form>
                            <input type="button" onclick="deductValueAndRevenue()" value="-" />
                            <input type="button" onclick="incrementValueAndRevenue();" value="+" />
                        </form>
                    </li>
                }
            </ul>
        </div>

Lastly, here is the JavaScript function being used:

function incrementValueAndRevenue() {
        var value = document.getElementById("items-sold").value;
        value++;
        document.getElementById("items-sold").value = value;

        var myJSON = { price: 35 };
        var revenue = myJSON.price * value;
        document.getElementById("total-revenue").value = revenue;
    }

I am looking for a way for the myJSON variable in the function to fetch the actual price from the corresponding item in the JSON file.

Answer №1

Did you give this a shot?

let jsonObject = JSON.parse(jsonData)[0];
 
jsonObject.Value

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

Guide on choosing a specific div element from a different page using AJAX

I have a Social Media platform with posts, and I am trying to display the newest ones using JavaScript (JS) and AJAX. I attempted to reload my page using AJAX and insert it into a div element, but now the entire website is loading within that div element, ...

Is it possible to dynamically update JSON files in AngularJS?

It appears that Angular JS may encounter difficulties updating content in .json files dynamically. I have noticed that I need to restart the server locally for Angular to acknowledge any new data. This behavior seems to be inherent in how AngularJS handl ...

updating the json file with new information rather than appending modifications to the existing data

I have a function that is used for writing to a json file: public function saveToJsonFile(array $data): void { if (file_exists('data/db.json')) { $content = $this->getJsonContent(); if ($content) { $data = arra ...

Is it possible to establish a connection between React and a MySQL Database?

I've been encountering issues with connecting to a remote database in React. Despite my efforts, I haven't been successful in establishing the connection. I have tried various solutions without any luck. The goal is simple - I just want to connec ...

Unable to display ChartJs within the same DIV on the webpage

I'm struggling to display the Pie Chart from ChartJs in the correct DIV when I click from the left DIV. Running the chart directly works fine, but I want them both on the same page in separate DIVs. I have separate HTML files for each link and they wo ...

The function for removing a specific element with a selector in JavaScript is

Take a look at this link: jsfiddle $('body').remove('p') I have encountered an issue where when I pass a selector to the remove() function, it doesn't seem to work correctly. However, if I use: $('body p').remove() ...

Using JSON strings and the .format() method in Python3

My goal is to create a JSON string using the .format() method. However, when I attempted to do so with the code below: TODO_JSON = '{"id": {0},"title": {1},"completed:" {2}}' print(TODO_JSON.format(42, 'Some Task', False)) I encounter ...

Issue with resetting JavaScript input value in onblur event

I have a function where I'm trying to clear the value of an input element, but it's not working as expected. The code looks like this: inputT1.onblur = function () { var pDomain = this.value; $.get("netutil/php/trial500.php", { ...

Preserving the jQuery object during an AJAX post操作

When using AJAX calls, I am looking to preserve the datatable object. See the code snippet below: $(function(){ function applyDataTables(options) { //datatable object var $datatable = $("#table1").dataTable(options); ...

JQuery: Techniques for accessing the assigned font of an element

Can the assigned font of an element be retrieved using jQuery? For example, if there is this CSS: #element { font-family: blahblah,Arial; } In the above case, the Arial font will be assigned to #element. Is it possible to extract that information using ...

The delay between initiating a Next JS route by clicking and the corresponding page actually loading

Just launched my website at this link: I am experiencing a delay of up to 2 seconds between clicking the header links and the page loading. The site works fine in development and on localhost, so I'm not sure why there's such a slowdown on the l ...

continuously adjust the cost

I'm struggling with incorporating a JavaScript function that is required for my school project. The task at hand is to create a store where the price updates dynamically when quantities are added or removed. The +/- buttons are functioning correctly; ...

Top method for establishing a mysql connection in Express version 4

Recently, I installed node-mysql and started running on express 4. Although I'm new to express, I am eager to learn the best practices for handling database connections. In my current setup, I have app.js var mysql = require('mysql'); //se ...

Creating a custom loading spinner using HTML and CSS

I am looking to create a spinner using just the <input> element. The only element I can utilize is <input type="text" placeholder="Select Date" class="sel1" /> How can I use CSS to implement a basic spinner in this scenario? ...

Unable to apply insertRule with keyframes

When using CSS without keyframes, insertRule functions perfectly. However, if a CSS with keyframes is used, an error occurs: Failed to execute 'insertRule' on 'CSSStyleSheet': Failed to parse the rule ... The following code works: ...

Error in Typescript: The property 'children' is not included in the type but is necessary in the 'CommonProps' type definition

Encountering this error for the first time, so please bear with me. While working on a project, I opened a file to make a change. However, instead of actually making any changes, I simply formatted the file using Prettier. Immediately after formatting, t ...

How can I create my own unique scrolling behavior in JavaScript?

Looking to create a similar effect as seen on this website: where the vertical scrollbar determines the movement of the browser "viewport" along a set path. I believe that using Javascript to track the scroll bar value and adjust background elements acco ...

Is it possible to display tooltips in amcharts based on specific conditions?

How can I display tooltip text in the chart based on a specific condition? I only want to show the tooltip text if the value is not equal to 0. Series.columns.template.tooltipText = `{valueY}s`; The tooltip currently displays the value of {valueY}, but I ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

Establish Mongoose query requirement according to the property of the document

Presently, I have a Mongoose Event document with attributes like startTime, endTime, and duration. In my node.js file, I am working on executing a query that fetches all Events where the start time is earlier than the current timestamp, and the end time is ...