epynic epynic - 2 months ago 16
Javascript Question

Find the parent and nearest element using jQuery

I have a simple form as

<tr>
<td> <input type="text" name="qty[]" placeholder="qty"/> </td>
<td> <input type="text" name="price[]" placeholder="price"/> </td>
<td> <input type="text" name="total[]" placeholder="Total"/> </td>
</tr>


we can have multiple row with the same as above.

What I need is when the User inputs the
qty
or
price
the row
total
needs to update.

What I tried

$('input[name=\'qty[]\']').on('change keyup', function(){
var qty = $(this).val();
var price = $(this).parent('tr').find('input[name=\'price[]\']').val();
});


price
is
undefined


Or is there an easier way to do it? Please check the Fiddle

UPDATE :

.parent(..)
selects the direct parent of each of the elements in the current set of elements. The first argument filters this set. The direct parent of your input element is the
td
element, not the
tr
element.

Updated Fiddle

Answer

first of, think about making your html as such:

<tr>
    <td> <input type="number" name="qty[]" placeholder="qty"/> </td>
    <td> <input type="number" name="price[]" placeholder="price"/> </td>
    <td> <input type="number" name="total[]" placeholder="Total"/> </td>
</tr>

Also. As far a javascript goes:

jQuery(document).on("change ,  keyup" , "input[name='qty[]'] , input[name='price[]']" ,function(){
     var parent_element = jQuery(this).closest("tr");
     var qty = jQuery(parent_element).find("input[name='qty[]']").val();
     var price = jQuery(parent_element).find("input[name='price[]']").val();
     if( qty.trim() != "" && price.trim() != "")
      {
        jQuery(parent_element).find("input[name='total[]']").val( parseFloat(qty) *parseFloat(price) );
      }
      else
      {
        jQuery(parent_element).find("input[name='total[]']").val("");
      }
});

EDIT :Better approach, properly taking into account empty fields