Search code examples
jqueryjquery-selectors

How to select tr sibling and input on table


I try select and get price after select product and return price on the respect input sibling tr.

I try

function getPrice() {
  $(this).closest('tr').find('input').val($(this).val());
};

and variations with nth-child() but I can not.

I need update price value

<!-- Django template tags -->
{% for item in items %}
<tr>
  <td>
    <select name="product" class="form-control" onchange="getPrice()">
      <!-- Django template tags -->
      {% for product in products %}
        <option value="{{product.pk}}">{{ product.title }}</option>
      {% endfor %}
    </select>
  </td>
  <td>
    <input name="price" class="form-control price" type="number" step="0.01">
  </td>
  <td>
    <input name="quantity" class="form-control" type="number" step="0.01">
  </td>
  <td>
    <span class="span-is-link no" onclick="removeRow()">
      <i class="fa fa-close"></i>
    </span>
  </td>
</tr>
{% endfor %}

<script>
  function getPrice() {
    // Initial test with get value of select.
    // jQuery
    // inpuy in equivalent line of tr
    $(this).closest('tr').find('input').val($(this).val());
  }
</script>

enter image description here


Solution

  • Your getPrice() function is not working because as you're calling it through the onchange HTML attribute, the this keyword will be window, that is, the browser global object, not your <select> element.

    A solution could be replacing getPrice() in your HTML onchange attribute with getPrice.call(this). That way, this inside your function will be the <select>.

    <select name="product" class="form-control" onchange="getPrice.call(this)">