tags:

views:

35

answers:

3

I can't get the right sum of two values.I want to sum the cena1 and kolicina. (cena1+kolicina) and (cena1*kolicina) My jquery code

<script type="text/javascript"> 
function izracunaj() {

    var sum = 0;
    $("#kolicina").each(function() {

    var cena = $("#artikel").val().split("-"); 
    var cena1 = cena[1]; // HERE I GET VALUE 0.17
    var kolicina = $("#kolicina").val(); // VALUE 10

        });
}

</script>
+3  A: 

You're dealing with strings, not numbers, looks like you want floats in which case you would use parseFloat() to get the number from the given string:

function izracunaj() {
  var sum = 0;
  $("#kolicina").each(function() {
      var cena = $("#artikel").val().split("-"); 
      var cena1 = parseFloat(cena[1]);
      var kolicina = parseFloat($("#kolicina").val());
      sum += cena1 * kolicinal;
  });
  //use sum
}

However, IDs should be unique, so I'm not sure why there's a .each() call here, it could be just:

function izracunaj() {
  var cena = parseFloat($("#artikel").val().split("-")[0]),
      kolicina = parseFloat($("#kolicina").val());
      sum = cena * kolicinal;
  //use sum
}
Nick Craver
This is one thing that ticks me off almost every day in Javascript. Language writers please take note: Addition and concatenation are NOT the same! Don't use the same operator for both!
AllenJB
I used this, but i get 0
Alen
@Alen - Do you have the markup this goes with?
Nick Craver
A: 

$("#kolicina").val(); is probably a string not a number. Try using parseFloat();

Jakub Konecki
+1  A: 

You could try using parseFloat on the values. e.g.

var answer = parseFloat(cena1) + parseFloat(kolicina);
Richard
I tryed var answer = parseFloat(cena1) + parseFloat(kolicina); this option but they don't sum me. i think the problem is in cena1, but don't now how.
Alen
Alen: Could it be that cena is "0,17" instead of "0.17"? The variable name sounds like this is from a country where "," is the decimal separator.
ammoQ
Yes you have right :D
Alen