JavaScript not found [object HTMLSpanElement], how i can fix that

  1. Values from form inputs will always be strings, so to add numbers together you need to coerce the string to a number. A couple of methods: 1) Number(str) or 2) +str.

  2. Your object of products/prices: there’s no need to have those prices as strings.

  3. The main problem you were having is that let costoTotal= document.getElementById("valor"); is only picking up the element and not the text content. We can use let costoTotal= document.getElementById("valor").textContent; for that, but then we need to coerce that to a number similarly to input values.

(Sidenote: at the moment your code doesn’t use the value from inputCompra which is why I asked about it in the comments. So the total will increase by 40 for bananas, for example, regardless of what is entered in that input.)

let btn = document.getElementById("buttonCarrito");
btn.addEventListener("click", agregar);

function agregar() {

  let Productos = {
    Manzana: 50,
    Banana: 40,
    Naranja: 30,
    Mandarina: 20
  }

  let frutaComprada = document.getElementById("inputProducto").value;
  let costoTotal = Number(document.getElementById("valor").textContent);
  let productoSeleccionado = Productos[frutaComprada];

  costoTotal = costoTotal + productoSeleccionado;

  valor.textContent = costoTotal;

}
<div class="container">
  <h1>Bienvenido a la tienda</h1>
  <input id="inputProducto" type="text" placeholder="Ingrese su producto">
  <br>
  <br>
  <input id="inputCompra" type="text" placeholder="Ingrese el número de artículos">
  <br>
  <br>
  <button id="buttonCarrito">Agregar al carrito</button>
  <p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>

Here’s a version that uses quantity in case you were curious.

let Productos = {
  Manzana: 50,
  Banana: 40,
  Naranja: 30,
  Mandarina: 20
}

const product = document.getElementById('inputProducto');
const quantity = document.getElementById('inputCompra')
const valor = document.getElementById('valor');
const btn = document.getElementById('buttonCarrito');

btn.addEventListener('click', agregar);

function agregar() {

  const frutaComprada = product.value;
  const itemQuantity = Number(quantity.value);
  const productoSeleccionado = Productos[frutaComprada];
  const subTotal = productoSeleccionado * itemQuantity;
  let costoTotal = Number(valor.textContent);

  costoTotal = costoTotal + subTotal;

  valor.textContent = costoTotal;

}
<div class="container">
  <h1>Bienvenido a la tienda</h1>
  <input id="inputProducto" type="text" placeholder="Ingrese su producto">
  <br>
  <br>
  <input id="inputCompra" type="text" placeholder="Ingrese el valor de su compra">
  <br>
  <br>
  <button id="buttonCarrito">Agregar al carrito</button>
  <p>El valor total de su compra es: <span id="valor"> 0 </span></p>
</div>

Leave a Comment