views:

55

answers:

3

There is problem with the following code. I am trying to Increase the dollar amount for all the numbers independently (by 0.01 per click). But it only seems to work on the first "content" class, not on the other 2. Each of these are identical besides the amount.

Layout:

<div class="content">
    <div class="item"><span class="number">$10.11</span><a href="#" class="incNumber"> Increase</a></div>
</div>
<div class="content">
   <div class="item"><span class="number">$5.04</span><a href="#" class="incNumber"> Increase</a></div>
</div>
<div class="content">
    <div class="item"><span class="number">$3.45</span><a href="#" class="incNumber"> Increase</a></div>
</div>

Script:

$(function () {
   $(".incNumber").click(function() {
      brother = $(this).closest('div').children('.number');
      amount = $(brother).html().replace(/[^\d\.]/g, "");
      amount = parseFloat(amount);

      $(brother).html('$'+String(amount.toFixed(2)));
      return false;
   });
});

This script seems to function fine. converting it to a float and then back seems to increase it by 0.01 however this is not intentional...

A: 

From the jQuery documentation you can find this:

In an HTML document, we can use .html() to get the contents of any element. If the selector expression matches more than one element, only the first one's HTML content is returned.

http://api.jquery.com/html/

You might use each to iterate over all elements found...

Yves M.
I think this is not the problem, `$(this).closest('div').children('.number')` will return one only element anyway (meaning there is only one element in the selection).
Felix Kling
A: 

For me, your code works without any unexpected behavior... it does nothing. But when I change this

amount = parseFloat(amount) + 0.01;

The increase button increases the individual numbers by 0.01

Jochem
Hmm. there must be more to this than i thought. I will investigate further.
FallingReign
A: 

I think you missed the incrementing. but anyways this is a modified version of ur code. I hope I got what you are trying to do.

$(function () {
    $(".incNumber").click(function() {
    brother = $(this).siblings('.number');
    amount = $(brother).html().replace(/[^\d\.]/g, "");
    amount = parseFloat(amount);
    amount = amount + 0.01;
    $(brother).html('$'+String(amount.toFixed(2)));
        return false;
    });
});
burntblark
Yeah, for some reason because I was converting the font with coufon, I didn't need the increment, coufon seemed to have caused strange rounding errors. Once I removed coufon and used a websafe font, the increment worked as intended.
FallingReign