Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

67
Vistas
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.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Have you tried using this?

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

parse.Price
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.