1

I have form which is making sum of numbers but I want that middle input to be skipped by jQuery for summing. Please help with this I'm posting code here. It surely must be the input tag because it sends data to PHP. I spent so much time to figure this out, but I can't see the problem.

jQuery

    var total;
    $("input.amount").keyup(function() {
        total = 0;
        $(this).parents("table").find("input.amount").each(function() {
            total += parseInt($(this).val());
        }).end().find("span.total").html(total);
    });

HTML

  <form class="calc">
    Form 1
    <br />
    <table border="0">
        <tr>
            <td>
                Amount 1
            </td>
            <td>
                <input class="amount" type="text" />
            </td>
        </tr>
        <tr>
            <td>
                Amount 2
            </td>
            <td>
                <input class="amount" type="text" />
            </td>
        </tr>
        <tr>
            <td>
                Amount 3
            </td>
            <td>
                <input class="amount" type="text" />
            </td>
        </tr>
        <tr>
            <td>
                Total Amount
            </td>
            <td>
                <span class="total">0</span>
            </td>
        </tr>
    </table>
    </form>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lasha
  • 467
  • 1
  • 4
  • 14
  • Middle input? Unfortunately we cannot read your mind. Can you please provide us more specific details? – Austin Brunkhorst May 18 '13 at 07:07
  • 1
    If I understood you correctly you want to skip `Amount 2` field to be added to the sum? If you mean that you can just change the input's class. You are matching elements by `input.amount` so if Amount 2 input doesn't have `amount` class it wont be catched by jQuery. – Paul Reed May 18 '13 at 07:27
  • Remove `class="amount"` in Amount 2 text box. – Lakshmana Kumar May 18 '13 at 07:37

1 Answers1

2

Simply change the HTML markup to give the input you wish to ignore a new class or data-* attribute.

<input class="amount ignored" type="text" />

Then check for the class in your .each() loop:

if(!$(this).hasClass('ignored'))
    total += parseInt($(this).val());

If you go down the data-* route, you could use:

<input class="amount" type="text" data-ignored="true" />

And check making sure that the data attribute is set:

if(!$(this).data('ignored'))
    total += parseInt($(this).val());
James Donnelly
  • 126,410
  • 34
  • 208
  • 218