Add onclick() values

Asked

Viewed 87 times

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 press another icon, I was supposed to increase the price to all the other prices you had been charged before, but instead, I add the values extensively in the div with id = "spent"

  • Question field is for question and answer field is for answers. There is no way to be clearer than that. Remember that [en.so] is not a forum. In fact, do the [tour] to learn the basics of the site. And do it soon, to avoid any possible embarrassment.

1 answer

1


As you yourself discovered, the problem is that by 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 sum them up, such as in:

tudo = parseInt(p+t);

Will stay:

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

In Javascript, the operator + concatenate two strings. So I’d be:

tudo = parseInt("15") 
     = 15;

In order 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.