JAVASCRIPT- How do I accumulate data-price tags when I click Product1 or Product2?

0

<!DOCTYPE HTML> <html>
 <head> <meta charset="utf-8"> 
	<script> function IndicarDistancia(laId){//Crear una referencia del elemento HTML con la id que se pasa por parámetro
  	var miDiv=document.getElementById(laId); //Obtener el valor de atributo 'data-precio' de la referencia miDiv
   	var attr=miDiv.getAttribute('data-precio'); //Obtener una referencia del elemento con id="precio"
  	 var miContenedor=document.getElementById('precio'); //Introducir en miContendor el precio correspondiente del producto
  	 miContenedor.innerHTML='El precio es '+ attr; 
	}</script> 
</head>
 <body> <!--Cada button tiene un valor en data-precio y al hacer clic se ejecuta la función IndicarDistancia a la que se le pasa por parámetro la id del button correspondiente --> 
 	<button data-precio="100€" id="uno" onClick="return IndicarDistancia('uno')"> Producto1</button>
 	<button data-precio="50€" id="otro" onClick="return IndicarDistancia('otro')"> Producto2</button> <div id="precio"></div>
</body>
 </html>
    
asked by Samuel Silva 03.03.2018 в 12:41
source

1 answer

0

To accumulate the price you should store the accumulated in a variable to be adding the price of the product pressed.

To be able to convert it to a problem-free number, it would be preferable if the data-precio property was simply the number, and you will add the euro symbol when displaying the data on the screen.

Another possible improvement is to add the event handler by code instead of the HTML code (in the onclick property). That way you save yourself having to do it one by one. And if you want to change it in the future, it will be much easier for you.

In the example that I give you below I have also omitted the step of id as an argument, since you can access the element pressed through the reserved word this .

var precioTotal = 0;

// Suma precio del producto al total
function IndicarDistancia(){
  //Obtener el valor de atributo 'data-precio' del botón
  var attr = this.getAttribute('data-precio');
  // Sumar al precio total
  precioTotal += parseInt(attr);
  //Obtener una referencia del elemento con id="precio"
   var miContenedor=document.getElementById('precio');
   //Introducir en miContendor el precio total
   miContenedor.innerHTML='El precio es '+ precioTotal + '€'; 
}

var botones = document.querySelectorAll('button[data-precio]');
botones.forEach(boton=> boton.addEventListener('click', IndicarDistancia));
<!--Cada button tiene un valor en data-precio y al hacer clic se ejecuta la función IndicarDistancia a la que se le pasa por parámetro la id del button correspondiente --> 
 	<button data-precio="100" id="uno"> Producto1</button>
 	<button data-precio="50" id="otro"> Producto2</button> <div id="precio"></div>
    
answered by 03.03.2018 / 12:58
source