Mir Abzal Ali Mir Abzal Ali - 6 months ago 58
Javascript Question

Onchange select item value set on the next column input field for each row in jquery

I'm trying to get the selected item's

data-price
to set on the next column's input field. It's working for first row but not working for each row.

How do I get this done?

<td>
<select class="clientType" name="type[]">
<option value="" disabled selected>Type</option>
<option data-price="3" value="3">R</option>
<option data-price="10" value="10">EB</option>
<option data-price="3" value="3">ND</option>
<option data-price="" value="">Special</option>
</select>
</td>
<td>
<input class="clientAmt" type="number" name="amount[]">
</td>


jQuery:

$('.clientType').change(function () {
$(this).each(function() {
$('.clientAmt').val($('option:selected', this).data('price'));
})
})

Answer

remove the each and go to the closest row to find the .clientAmt

$('.clientType').change(function() {
  $(this).closest('tr').find('.clientAmt').val($('option:selected', this).data('price'));
});

DEMO

$('.clientType').change(function() {
  $(this).closest('tr').find('.clientAmt').val($('option:selected', this).data('price'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <select class="clientType" name="type[]">
        <option value="" disabled selected>Type</option>
        <option data-price="3" value="3">R</option>
        <option data-price="10" value="10">EB</option>
        <option data-price="3" value="3">ND</option>
        <option data-price="" value="">Special</option>
      </select>
    </td>
    <td>
      <input class="clientAmt" type="number" name="amount[]">
    </td>
  </tr>
  <tr>
    <td>
      <select class="clientType" name="type[]">
        <option value="" disabled selected>Type</option>
        <option data-price="3" value="3">R</option>
        <option data-price="10" value="10">EB</option>
        <option data-price="3" value="3">ND</option>
        <option data-price="" value="">Special</option>
      </select>
    </td>
    <td>
      <input class="clientAmt" type="number" name="amount[]">
    </td>
  </tr>
</table>

Comments