iamjonesy
iamjonesy

Reputation: 25122

Undefined error getting parents childs input value

I have a table that looks like this:

<table>
    <tr>
       <td class="packing-vol">0.19</td>
       <td class="qty-cell"><input type="text" name="qty[]" class="qty" value="2" /></td>
     </tr>
     <tr>
       <td class="packing_total">0.70</td>
       <td class="qty-cell"><input type="text" name="qty[]" class="qty" value="1" /></td>
     </tr>
</table>

I'm looping through each occurence of .packing-vol getting it's text, then I want to get the qty from the same row so I go up to it's parent then drill into the .qty class. But when I alert(qty) i get 'undefined' message.

var total = 0;

jQuery('.packing-vol').each(function(i) {

    var qty = jQuery(this).parent("td.qty-cell .qty").val();
    alert(qty);

    var cur = parseFloat(jQuery(this).text());
    if(!isNaN(cur)){
        total = total + cur;
    }

});

Upvotes: 0

Views: 818

Answers (3)

Marco Johannesen
Marco Johannesen

Reputation: 13134

parent is just one level upwards. You can't use it to go inside trees again.

parents is multiple levels upwards. You can't use it to go inside trees again.

You can use parent/parents and then use find to do what you want, or even better:

var total = 0;
jQuery('.packing-vol').each(function(i) {

    var qty = jQuery(this).parent().children('.qty-cell').children('.qty').val();
    alert(qty);

    var cur = parseFloat(jQuery(this).text());
    if (!isNaN(cur)){
        total = total + cur;
    }
});

You could also use find, but it is slower than going directly inside, because it has to search the DOM object.

But you could also do:

var qty = jQuery(this).parent().find("td.qty-cell .qty").val();

Upvotes: 2

Ankur
Ankur

Reputation: 33637

Instead of

var qty = jQuery(this).parent("td.qty-cell .qty").val();

Try:

var qty = jQuery(this).parent().find(".qty").val();

Upvotes: 1

Igor Dymov
Igor Dymov

Reputation: 16460

I think you should do this:

var qty = jQuery(this).parent().find("td.qty-cell .qty").val();

You need to go 1 level up (using .parent) and then find your field inside with .find

Upvotes: 3

Related Questions