поле суммы значения ключа javascript ajax codeigniter - PullRequest
1 голос
/ 07 августа 2020

я хочу подсчитать поле id = "HargaPart", если отмечено = true.

это мой код просмотра:

<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
                <h3 class="modal-title" id="myModalLabel">Tambah Pemeliharaan</h3>
            </div>
            <form id="frmSparepart" class="form-horizontal" method="post" action="<?php echo base_url()?>Data/Pemeliharaan/Tambah">
                <div class="modal-body">
                    <div class="form-group">
                    <label class="control-label col-xs-3">Nama Kendaraan</label>
                        <div class="col-xs-8">
                            <select class="form-control"  name="id_kendaraan" id="id_kendaraan" required>
                            <option>Pilih Kendaraan</option>
                            <?php
                            if(!empty($kendaraan_)) {
                            foreach ($kendaraan_ as $isi) {
                            ?>
                            <option value="<?php echo $isi['id_kendaraan']?>"><?php echo $isi['nama']?> - <?php echo $isi['platno']?></option>
                            <?php }} ?>
                            </select>
                        </div>
                    </div>
                    <?php
                    $index =0;          
                    foreach ($subkriteria_ as $kr_key => $kriteria) {
                    ?>
                    <div class="form-group">
                        <label class="control-label col-xs-3"><?php echo $kriteria['nama_kriteria'] ?></label> 
                        <div class="col-xs-8">
                                <input type="hidden" name="status_pemeliharaan" value="1" class="form-control">
                                <input type="hidden" name="id_kriteria[]" value="<?php echo $kriteria['id_kriteria'] ?>" class="form-control">  
                            <?php if(!empty($kriteria['sub'])) { ?> 
                            <select class="form-control"  name="isi_kriteria[]" required>
                                <option>Pilih Sub Kriteria</option>
                                <?php $no = 1; foreach ($kriteria['sub'] as $data)     { ?>
                                <option value="<?php echo $data['value'] ?>"><?php echo $data['namasubkriteria'] ?> - <?php echo $data['value'] ?></option>
                                <?php  $no++; } ?>
                            </select>
                            <?php } else if($kriteria['link']=='tahun_beli') { ?>
                                <input id="tahun" name="isi_kriteria[]" value="" class="form-control" type="text" placeholder="Isi Kriteria..." readonly required>
                            <?php } else if($kriteria['link']=='sparepart') { ?>
                            <input id="counterSparepart" name="isi_kriteria[]" value="" class="form-control" readonly type="number" required> 
                            <?php } else { ?>
                                <input name="isi_kriteria[]" value="" class="form-control" type="number" placeholder="Isi Kriteria..." required>
                            <?php } ?>
                        </div>
                    </div>
                    <?php } ?>
                    <div class="form-group">
                        <label class="control-label col-xs-3" >Biaya Total</label>
                        <div class="col-xs-8">
                            <input id="totalBiaya" name="biaya" value="" class="form-control" type="number" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label col-xs-3"></label>
                        <div class="col-xs-8">
                            <ul id="sparepartList" style="list-style-type: none; padding: 0;">
                            </ul>
                        </div>
                    </div>
                </div> 
                <div class="modal-footer">
                    <button class="btn" data-dismiss="modal" aria-hidden="true">Tutup</button>
                    <button class="btn btn-info">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript">
function onChangeCheckbox() {
    var rTotal = 0;
    var sum = 0;
    var input = $('input[type="checkbox"]');
    var checkboxes = input.length;
    var harga = $('#HargaPart').val();
    for (var sel = 0; sel < checkboxes; sel++) {
        if (input[sel].checked) rTotal += 1;
        if (input[sel].checked) sum += parseInt(harga);
    }
    $('#counterSparepart').val(rTotal);
    $('#totalBiaya').val(sum);
}

$(document).ready(function(){
    $('#id_kendaraan').on('input',function(){
        var id_kendaraan=$(this).val();
        $.ajax({
            type : "POST",
            url  : "<?php echo base_url('Data/Pemeliharaan/GetKendaraanById')?>",
            dataType : "JSON",
            data : {id_kendaraan: id_kendaraan},  
            cache:false,
            success: function(data){
                $('#sparepartList').empty(); // clear all sparepart checkboxes           
                $('#tahun').val(data.tahun_beli);
                // $('[name="id_jenis"]').val(data.id_jenis);
                $.each(data.spareparts, function (key, value) {
                    let li = $('<li><input onchange="onChangeCheckbox()" type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '">&nbsp;' +
                             value.sparepart +' Rp. <input id="HargaPart" name="HargaSparepart" value="'+ value.harga +'" class="form-group" type="text" readonly></li>');
                    $('#sparepartList').append(li);
                });
            }
        });
        return false;
    });
});
</script>

это мой контроллер:

function GetKendaraanById(){
        $id_kendaraan=$this->input->post('id_kendaraan');
        $data=$this->PemeliharaanModel->GetById($id_kendaraan);
        echo json_encode($data);
      }

это моя модель:

function GetById($id_kendaraan){
        $this->db->select('*');
        $this->db->from('tb_kendaraan');
        $this->db->where('tb_kendaraan.id_kendaraan',$id_kendaraan);
        $query_kendaraan = $this->db->get();
        
        $hasil = false;
        if($query_kendaraan->num_rows() > 0)
        {
            $data_kendaraan = $query_kendaraan->row();
            $hasil = [
                'tahun_beli' => $data_kendaraan->tahun_beli,
                'id_jenis' => $data_kendaraan->id_jenis,
                'id_merk' => $data_kendaraan->id_merk,
                'spareparts' => [] // empty array, to be filled with spareparts data
            ];
            $this->db->select('*');
            $this->db->from('tb_sparepart');
            $this->db->where('tb_sparepart.id_jenis', $data_kendaraan->id_jenis);
            // $this->db->where('tb_sparepart.id_merk', $data_kendaraan->id_merk);
            $query_sparepart = $this->db->get();
            
            foreach ($query_sparepart->result() as $data_sparepart) {
                $spareparts = [
                    'id_sparepart' => $data_sparepart->id_sparepart,
                    'sparepart' => $data_sparepart->sparepart,
                    'harga' => $data_sparepart->harga,
                ];
                array_push($hasil['spareparts'], $spareparts);
            }
        }
        return $hasil;
    }

Сумма поле Харга

если я попробую этот код, результатом будет просто сумма HargaPart в запасной части "roda gede sekali" 500 + 500 = 1000, в этом коде должно быть 500 + 100 = 600, потому что я проверил 2 запасные части с not то же значение ...

как суммировать все value.harga если checkbox = true?

Ответы [ 2 ]

1 голос
/ 07 августа 2020

Вы можете использовать each l oop для перебора значений отмеченных флажков, а затем получить значение HargaSparepart, используя .next(), потому что в вашем html он находится рядом с checkbox.

Код демонстрации :

function onChangeCheckbox() {
  var rTotal = 0;
  var sum = 0;

//loop through ul->checkboxes 
  $('#sparepartList input[type="checkbox"]:checked').each(function() {
  //get next input  HargaSparepart
    var harga = $(this).next('input[name=HargaSparepart]').val()
    rTotal += 1; // add 1
    sum += parseInt(harga); //add to sum

  })
//add values to inputs
  $('#counterSparepart').val(rTotal);
  $('#totalBiaya').val(sum);

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
  <label class="control-label col-xs-3">Biaya Total</label>
  <div class="col-xs-8">
    <input id="totalBiaya" name="biaya" value="" class="form-control" type="number" required>
  </div>
</div>

<div class="form-group">
  <label class="control-label col-xs-3"></label>
  <div class="col-xs-8">
    <ul id="sparepartList" style="list-style-type: none; padding: 0;">
      <li><input onchange="onChangeCheckbox()" type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '">Something Rp. <input id="HargaPart" name="HargaSparepart" value="500" class="form-group" type="text" readonly></li>
      <li><input onchange="onChangeCheckbox()" type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '">&nbsp; Something1 Rp. <input id="HargaPart" name="HargaSparepart" value="100" class="form-group" type="text" readonly></li>
      <li><input onchange="onChangeCheckbox()" type="checkbox" name="id_sparepart[]" value="' + value.id_sparepart + '">&nbsp;Something2 Rp. <input id="HargaPart" name="HargaSparepart" value="200" class="form-group" type="text" readonly></li>

    </ul>
  TotalBiaya : 
    <input type="text" id="counterSparepart">
  </div>
</div>
0 голосов
/ 07 августа 2020

Попробуйте этот код

$('#HargaPart').change(function (){
  var total = 0;
  $('#HargaPart:checked').each(function(){ // iterate through each checked element.
    total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
  });     
  $("#total").val(total); 
});
...