Jquery find subelement from $(this)

Faiyet picture Faiyet · Dec 1, 2011 · Viewed 11.1k times · Source

I have a table in in which every row contains a form. see below

<table>
<tr><th>Fee Type</th><th>Amount</th><th>% Discount</th><th>Discounted Amount</th><th>Payable to</th><th>Remove</th></tr>    
<tr>
   <form>
         <td></td>
         <td class="cost"></td>
         <td> <input /> </td>
         <td class="discount"></td>
         <td></td>
   </form>
<tr>
</table>

Now my intention is to have a global save button which will loop through each form and perform an ajax post. see below

    function saveEditedFees(){
        $("#savefeechanges").click(function(){
            $("#feestable form").each(function(){
                alert( $(this).attr('id') );
            });
        });
    }

My problem is accessing values for the "td" using the $(this) for the elements with class "cost" and "discount" I tried

alert( $(this).find("td").eq(2).html() );
alert($(this).siblings('.cost').text());
alert($("td .cost" ,this).text());

Basically, I am trying to test if the value contained in the <td class="cost"> is equal to the <td class="discount"> , this way i will selectively do an ajax post.

Please help.

Answer

RightSaidFred picture RightSaidFred · Dec 1, 2011

Invalid markup.

You have a <form> as a child of <tr>.

In Chrome, the HTML is rendered as:

<tr>
   <form></form>
         <td></td>
         <td class="cost"></td>
         <td> <input> </td>
         <td class="discount"></td>
         <td></td>
</tr>

As you can see, the <form> no longer has any content.

And remember that .eq() takes a zero-based index, so it should be:

$(this).find("td").eq(1)

...to get the .cost element.