Search code examples
javascriptjquerysubtotal

Javascript calculate total


I have this code :

http://jsfiddle.net/VAkLn/6/

When i add a table : http://jsfiddle.net/VAkLn/7/ this stop working. Why?

Solved:

I change This: price = self.next(".price"), To: price = $(".price"),


Solution

  • The reason your first example works is because tr and td elements are only valid in a table element. The browser effectively strips out those invalid tags in the DOM which leaves you with a structure similar to:

    <body>
        <input type="input" size="3" class="qta">
        <input type="input" size="7" class="price">
        TOTALE: <input type="input" id="total" size="7" ;="">
    </body>
    

    Check it out in Firebug or Webkit Inspector.

    The next() selector works here because input.price is the immediately following sibling of each element in the set of matched elements.

    As soon as you include a wrapping table element, the tr and td elements are valid in the structure and get placed in the DOM as you would expect:

    <body>
        <table width="520" border="0" align="center" cellpadding="3" cellspacing="0">
            <tbody>
                <tr>
                    <td width="40" bgcolor="#009966" class="whyte">
                        <input type="input" size="3" class="qta">
                    </td>
                    <td width="100" bgcolor="#009966" class="whyte">
                        <input type="input" size="7" class="price">
                    </td>
                </tr>
            </tbody>
        </table>
        TOTALE: <input type="input" id="total" size="7" ;="">
    </body>
    

    This breaks the next() selector because input.price is no longer the immediately following sibling of each element in the set of matched elements.

    The solution is to modify your jQuery selector for input.price to navigate the new structure:

    price = self.parents('tr').find(".price"),
    

    Updated your fiddle.