Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

299
Views
How to use a key from local Json file as variable in JavaScript function?

I have small system that needs to track sales. The point is to be able to click on a specific item and the total Value (ie. items sold) and the total Revenue goes up accordingly.

I have a button with a JS function called incrementValueAndRevenue() that works like it is supposed to. But I can only get it to work by declaring Json within the function itself, but would like to make it so that for each item in my local Json file the total price differs according to how many of what specific item has been clicked.

This is done is Razor Pages btw.

Here's my Json:

[
  {
    "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's my HTML

<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="decuctValueAndRevenue()" value="-" />
                            <input type="button" onclick="incrementValueAndRevenue();" value="+" />
                        </form>
                    </li>
                }
            </ul>
        </div>

And here's my JavaScript function

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;
    }

In the function is where I'd like the myJSON variable to to know what the price is from the actual Json File.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Have you tried using this?

const parse = JSON.parse(myJson)[0];

parse.Price
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!