gierg gierg - 28 days ago 9
jQuery Question

Set value from textbox to another textbox

I have a markup like this:

<div class="margin-bottom-sm col-sm-2">
<input type="text" class="form-control" name="txtketdetail[]" id="txtketdetail" placeholder="Nama detail akun" required />
</div>
<div class="margin-bottom-sm col-sm-2">
<input type="text" class="form-control input-number" name="txtvolume[]" id="txtvolume" placeholder="Volume/Jumlah" required />
</div>
<div class="margin-bottom-sm col-sm-2">
<input type="text" class="form-control input-number" name="txthrgsatuan[]" id="txthrgsatuan" placeholder="Harga satuan" required />
</div>
<div class="margin-bottom-sm col-sm-2">
<input type="text" class="form-control input-number" name="txtjmlbiaya[]" id="txtjmlbiaya" placeholder="Jumlah biaya" required />
</div>


$('input[id^="txthrgsatuan"]').on('change', function() {
$('input[id^="txthrgsatuan"]').each(function() {
$(this).parent().next().children().val($(this).val()*$(this).parent().prev().children().val());
});
});


I want to multiply
txthrgsatuan
with
txtvolume
and have the end result appear in
txtjmlbiaya
event trigger change
txthrgsatuan
. However there are troubles when I add another input with the same
name
an
id
. For more details see the picture below.

enter image description here

Answer

First of all change duplicate id's to classes. Then set an input event on the desired input fields, fetch values and set them accordingly.

Here is a working demo.

$(function() {

  $(document).on("input", ".txthrgsatuan", function() {
    var val = $(this).val();
    var otherVal = $(this).parent().prev().children().val();
    $(this).parent().next().children().val(val * otherVal);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="margin-bottom-sm col-sm-2">
  <input type="text" class="form-control txtketdetail" name="txtketdetail[]" placeholder="Nama detail akun" required />
</div>
<div class="margin-bottom-sm col-sm-2">
  <input type="text" class="form-control input-number txtvolume" name="txtvolume[]" placeholder="Volume/Jumlah" required />
</div>
<div class="margin-bottom-sm col-sm-2">
  <input type="text" class="form-control input-number txthrgsatuan" name="txthrgsatuan[]" placeholder="Harga satuan" required />
</div>
<div class="margin-bottom-sm col-sm-2">
  <input type="text" class="form-control input-number txtjmlbiaya" name="txtjmlbiaya[]" placeholder="Jumlah biaya" required />
</div>

Comments