简体   繁体   中英

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;
    }

});

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

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();

Instead of

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

Try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM