Add values onclick ()

0

I have this code:

var tudo=0;
function muda(a){
  o=$("#"+a).attr("data-ocupado");
  var t = $("#gasto").html();
  if(o==1){
    alert("Lugar já Ocupado!");
  }else{
  p=$("#"+a).attr("data-preco");
  var confirma = confirm("Deseja alugar este lugar? \n Preço: "+p+"€");
  if(confirma == true){
    tudo = parseInt(p+t);
    alert(p);
    $("#"+a).attr("data-ocupado", "1");
  $('#'+a).css({
        'color': 'red'
    });
    $("#gasto").html(tudo)
  }
}
}

With this html and php

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<div>
  <?php
  $a=0;
  while($a<300){
    $a++;
    if($a%5==0){
      $vazio="&nbsp;&nbsp;";
    }else{
      $vazio="";
    }
    if($a%50==0){
      $extra ="<br>";
    }else{
      $extra="";
    }
    $preco=rand(0, 40);
  ?>
  <span style="background-color:silver;color:black;cursor:pointer;" data-ocupado="0" data-preco="<?=$preco; ?>" id="<?=$a; ?>" onclick="muda(<?=$a; ?>)"><i class="fa fa-user"></i></span><?=$vazio; ?><?=$extra; ?>
  <?php } ?>
</div>

But whenever I load another icon, I was supposed to increase the price to all the other prices that I had loaded before, but instead, add the values extensively in the div with id="spent"

    
asked by anonymous 25.05.2017 / 22:24

1 answer

1

As you yourself discovered, the problem is that when doing:

var t = $("#gasto").html();
var p = $("#"+a).attr("data-preco");

Both variables will be of type string , for example, "1" and "5" , respectively. If you just try to add them, just like in:

tudo = parseInt(p+t);

It will be:

tudo = parseInt("1" + "5");

In JavaScript, the + operator concatenates two strings . So it would look like:

tudo = parseInt("15") 
     = 15;

For the sum to be done correctly, you need to convert the values to integers before the operation:

tudo = parseInt(p) + parseInt(t);
     = parseInt("1") + parseInt("5");
     = 1 + 5;
     = 6;
    
25.05.2017 / 23:28