My goal is to retrieve the value of "hargaJual" when I choose an option. However, when I add a new row to the table and select a different option, only the first row's "Harga" value changes while the second row remains empty.
Take a look at the outcome:
https://i.sstatic.net/YCfbW.png
<td>
<select class="custom-select" id="kodeSparepart" name="kodeSparepart[]">
<option value=""> --Select Sparepart-- </option>";
@foreach($sparepart as $s) {
<option value="{{ $s['kodeSparepart'] }}" data-price="{{ $s->hargaJual }}"> {{ $s['namaSparepart'] }} </option>";
}
@endforeach
</select>
</td>
<td>
<input class="form-control" type="text" id="hargaJualTransaksi" name="hargaJualTransaksi[]" autocomplete="off" readonly>
</td>
Additionally, here is the associated JavaScript:
// Insert new row into table
$(function(){
$('#addMore').on('click', function() {
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
});
$(document).on('click', '#remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>=1) {
$(this).closest("tr").remove();
} else {
alert("Sorry! Unable to remove the first row!");
}
});
});
// Populate hargaJualTransaksi field
$(function() {
$('#kodeSparepart').on('change', function(){
var price = $(this).children('option:selected').data('price');
$('#hargaJualTransaksi').val(price);
});
});