简体   繁体   中英

How to display data in input from selecting option in drop down with database MYSQL?

I have a problem with display data in the input after selected items in database. because I use a dynamic row. I selected data from first row, and data display on a first row input text. and then I add a new row, and I selected data from the second row. and data display on first row input text, not second row ??

Image From the Problem

Here is My HTML

<table class="table-bordered table item" id="t1">
    <thead>
        <tr>
            <th width="35%" class="text-center">Nama Barang</th>
            <th width="19%"class="text-center">Harga</th>
            <th width="12%" class="text-center">Qty</th>
            <th width="14%" class="text-center">Satuan</th>
            <th width="20%" class="text-center">Total Harga</th>
            <th><button type="button" class="btn btn-success btn-sm addRow">+</button></th>
        </tr>
    </thead>
    <tbody>
        <tr class="item">
            <td>
                <select onchange="changeValue(this.value)" class="selectReason" id="reason" name="reasontxt[]" required>
                    <option value=""  selected="" disabled="">-- Silahkan Pilih --</option>
                    <optgroup label="Nama Bahan Baku">
                        <?php 
                            $query = mysqli_query($koneksi, "select * from bahan a, kategori_bahan b, satuan c WHERE a.id_kategori_bahan=b.id_kategori_bahan and a.id_satuan = c.id_satuan order by nm_bahan asc"); 
                            $result = mysqli_query($koneksi, "select * from bahan a, kategori_bahan b, satuan c WHERE a.id_kategori_bahan=b.id_kategori_bahan and a.id_satuan=c.id_satuan order by nm_bahan asc");  
                            $jsArray = "var prdName = new Array();\n";
                            while ($row = mysqli_fetch_array($result)) {  
                                echo '<option value="' . $row['nm_bahan'] . '">' . $row['nm_bahan'] . '</option>';  
                                $jsArray .= "prdName['" . $row['nm_bahan'] . "'] = {id_satuan:'" . addslashes($row['nm_satuan']) . "',harga:'".addslashes($row['harga'])."'};\n";
                            }
                            ?>
                    </optgroup>
                </select>
            </td>

            <td>
                <input type="text" name="harga[]" placeholder="Harga" id="harga" class="form-control price amount" onkeypress="return hanyaAngka(event)" autocomplete="off" required />
            </td>
            <td>
                <input type="text" name="qty[]" placeholder="Qty" class="form-control qnty amount" value="0" onkeypress="return hanyaAngka(event)" autocomplete="off" required />
            </td>
            <td>
                <input type="text" name="satuan[]" placeholder="Satuan" id="id_satuan" class="form-control" onkeypress="return hanyaAngka(event)" readonly>
            </td>
            <td>
                <input type="text" name="harga_total[]" placeholder="Total Harga" class="form-control totalharga" onkeypress="return hanyaAngka(event)" autocomplete="off" readonly />
            </td>
        </tr>
    </tbody>
</table>

and this is my jQUERY and JavaScript

<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue(id){
document.getElementById('harga').value = prdName[id].harga;
document.getElementById('id_satuan').value = prdName[id].id_satuan;
};
window.onload=function(){

    $(document).ready(function () {

        var r = 1;
        $('.addRow').click(function () {
            r++;
            $('#t1').append('<tr id="row' + r + '" class="item"><td><select onchange="changeValue(this.value)" class="selectReason" id="reason" name="reasontxt[]" required><option value=""  selected="" disabled="">-- Silahkan Pilih --</option><optgroup label="Nama Bahan Baku"><?php $query=mysqli_query($koneksi, "select * from bahan a, kategori_bahan b, satuan c WHERE a.id_kategori_bahan=b.id_kategori_bahan and a.id_satuan=c.id_satuan order by nm_bahan asc"); $result = mysqli_query($koneksi, "select * from bahan a, kategori_bahan b, satuan c WHERE a.id_kategori_bahan=b.id_kategori_bahan and a.id_satuan=c.id_satuan order by nm_bahan asc");  $jsArray = "var prdName = new Array();\n";while ($row = mysqli_fetch_array($result)) {  echo '<option value="' . $row['nm_bahan'] . '">' . $row['nm_bahan'] . '</option>';  $jsArray .= "prdName['" . $row['nm_bahan'] . "'] = {id_satuan:'" . addslashes($row['nm_satuan']) . "',harga:'".addslashes($row['harga'])."'};\n";}?></optgroup></select></td><td><input type="text" name="harga[]" placeholder="Harga" id="harga" class="form-control price amount" onkeypress="return hanyaAngka(event)" autocomplete="off" required /></td><td><input type="text" name="qty[]" placeholder="Qty" class="form-control qnty amount" value="0" onkeypress="return hanyaAngka(event)" autocomplete="off" required /></td><td><input type="text" name="satuan[]" placeholder="Satuan" id="id_satuan" class="form-control" onkeypress="return hanyaAngka(event)" readonly/></td><td><input type="text" name="harga_total[]" placeholder="Total Harga" class="form-control totalharga" onkeypress="return hanyaAngka(event)" autocomplete="off" readonly /></td><td><button type="button" name="remove" id="' + r + '" class="btn btn-danger btn-sm btn_remove">x</button></td></tr>');
            $(".selectReason").select2({dropdownParent: $('#TambahData .modal-content'),width:'100%'});
        });
        $(document).on('click', '.btn_remove', function () {
            var button_id = $(this).attr("id");
            $('#row' + button_id + '').remove();
            calcAll();
        });
        $(document).on("keyup", ".amount", calcAll);
    });
    function calcAll() {

        $(".item").each(function () {
            var qnty = 0;
            var price = 0;
            var totalharga = 0;
            var diskon = 0;             
            var uangmuka = 0;

            if (!isNaN(parseInt($(this).find(".qnty").val()))) {
                qnty = parseInt($(this).find(".qnty").val());
            }
            if (!isNaN(parseInt($(this).find(".price").val()))) {
                price = parseInt($(this).find(".price").val());
            }
            if (!isNaN(parseInt($(this).find(".uangmuka").val()))) {
                uangmuka = parseInt($(this).find(".uangmuka").val());
            }
            if (!isNaN(parseInt($(this).find(".diskon").val()))) {
                diskon = parseInt($(this).find(".diskon").val());
            }


            totalharga = qnty * price;
            $(this).find(".totalharga").val(totalharga.toFixed());
        });

        var sum = 0;
        $(".totalharga").each(function () {
            if (!isNaN(this.value) && this.value.length != 0) {
                sum += parseInt(this.value);
            }
        });
        $("#subtotal").val(sum.toFixed());


        var diskon = 0;
        if (!isNaN(parseInt($("#diskon").val()))) {
            diskon = parseInt($("#diskon").val());
            }


        var total = 0;
        if (!isNaN(parseInt($("#total").val()))) {
            total = parseInt($("#total").val());
            }
        total = sum - (sum*(diskon/100));
        $("#total").val(total.toFixed());
    }
}
</script>

Seems to be an issue of selector (ID in this case). If I understand your scenario correctly, when adding a row then selecting a "Nama Barang", you expect the column "Harga" to be filled with the "harga" value associated with the selected dropdown value, right?

When adding rows, every input has the same ID than the previous row's inputs. So when calling the changevalue() function, javascript will select the first element with the "harga" ID. So you will always be updating the first row. Beware the <tr id="row" which can lead you to troubles as well.

First you should use class="harga" instead of id="harga" .

Then you could modify your script with something like:

on the select: onchange="changeValue(this)" and in the javascript:

function changeValue(select){
    var id = select.value;
    var row = $(select).closest(".item");
    row.find(".harga").value = prdName[id].harga;
    row.find(".id_satuan").value = prdName[id].id_satuan;
}

I've simplified a bit your code with my suggested changes here . Keep in mind that this code is not optimized, still has redundancies and wrong practices (inline styles, repeated code, not optimized mysql queries), and has not been tested. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM