Dj Genexxe Dj Genexxe - 5 months ago 20
jQuery Question

Change value of the next element

I have three text fields per row in my table.

<tr>
<td><input type="text" data-type="number" name="qty[]" /></td>
<td><input type="text" data-type="number" name="ucost[]" /></td>
<td><input type="text" data-type="number" name="total[]" readonly /></td>
</tr>
<tr>
<td><input type="text" data-type="number" name="qty[]" /></td>
<td><input type="text" data-type="number" name="ucost[]" /></td>
<td><input type="text" data-type="number" name="total[]" readonly /></td>
</tr>


The value of the text field named
total[]
per row must be (
qty * ucost
).
If the user input value to the
qty
field, the corresponding total field must be changed.

How to do it using the name attribute?
I tried this code,

$(document).on('keyup', "input[name='qty[]']", function(e) {
if (e.which >= 37 && e.which <= 40) {
e.preventDefault();
}
$("input[name='total[]']").val() = ($("input[name='ucost[]']").val() * $("input[name=qty[]']").val());
});


But it is not working.

Answer

You are using val() method incorrectly. You can use closest() and find() methods like following.

$(document).on('keyup', "input[name='qty[]'], input[name='ucost[]']", function(e) {
  if (e.which >= 37 && e.which <= 40) {
    e.preventDefault();
  }

  var qty = $(this).closest('tr').find('input[name="qty[]"]').val();
  var cost = $(this).closest('tr').find('input[name="ucost[]"]').val();
  var total = $(this).closest('tr').find('input[name="total[]"]');

  total.val(qty * cost);
});

$(document).on('keyup', "input[name='qty[]'], input[name='ucost[]']", function(e) {
  if (e.which >= 37 && e.which <= 40) {
    e.preventDefault();
  }

  var qty = $(this).closest('tr').find('input[name="qty[]"]').val();
  var cost = $(this).closest('tr').find('input[name="ucost[]"]').val();
  var total = $(this).closest('tr').find('input[name="total[]"]');

  total.val(qty * cost);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="text" data-type="number" name="qty[]" />
    </td>
    <td>
      <input type="text" data-type="number" name="ucost[]" />
    </td>
    <td>
      <input type="text" data-type="number" name="total[]" readonly />
    </td>
  </tr>
  <tr>
    <td>
      <input type="text" data-type="number" name="qty[]" />
    </td>
    <td>
      <input type="text" data-type="number" name="ucost[]" />
    </td>
    <td>
      <input type="text" data-type="number" name="total[]" readonly />
    </td>
  </tr>
</table>

Comments