0

Hello Guys!

Please i need help with my dynamic table, everything seems to be working fine except for my onchange event for each dynamically added row, it only inserts into the first row, but when i select an option from the second added row, the feilds to be updated from the database remains blank.

I used alert to check, and the onchange seems to be working on all rows just that it is only the first row that changes are effected to the required fields. Bellow is my code for your review.

//php script at the top of the page that populates select option data from the database

<?php
    $query1 = "SELECT * FROM products";
    $result1 = mysqli_query($con, $query1);
    $options = "";
    while($row3 = mysqli_fetch_array($result1))
    {
        $options = $options."<option value='$row3[1]'>$row3[2]</option>";
    }

?>

//My Javascript

<SCRIPT language="javascript">
//function that increases the table row
function addRow(dataTable) {
    var table = document.getElementById("dataTable");
    var rowCount = table.rows.length;
    if (rowCount < 4) { // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);
        var colCount = table.rows[1].cells.length;
        row.id = 'row_'+rowCount;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.outerHTML = table.rows[1].cells[i].outerHTML;            
        }
        var listitems= row.getElementsByTagName("input")
        for (i=0; i<listitems.length; i++) {
            listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
        }

    } else {
        alert("Maximum Row Reached.");
    }
}
//function that reduces the table row
function deleteRow(dataTable) {
    var table = document.getElementById("dataTable");
    var rowCount = table.rows.length;
    for (var i = 1; i < rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if (null !== chkbox && true === chkbox.checked) {
            if (rowCount <= 2) { // limit the user from removing all the fields
                alert("Cannot Remove all the Rows.");
                break;
            }
            table.deleteRow(i);
            rowCount--;
            i--;
        }
    }
}
//function that handles the summing of each row & all last column
function calculate(elementID) {
    var mainRow = document.getElementById(elementID);
    var myBox12 = mainRow.querySelectorAll('[id=item')[0].value;
    var myBox23 = mainRow.querySelectorAll('[id=descript')[0].value;
    var myBox1 = mainRow.querySelectorAll('[id=uprice')[0].value;
    var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
    var total = mainRow.querySelectorAll('[id=qty')[0];
    var multiplier = Number(myBox2) || 0;
    var myResult1 = myBox1 * multiplier;
    var mresult = myResult1.toFixed(2);                          
    total.value = mresult;
    var confirm = 10;
    var colCount;
    var table = document.getElementById("dataTable");
    let rows = [...table.querySelectorAll('[name*=qty]')];
    let total2 = rows.reduce((prev, current)=>{
        let to_be_added = Number(current.value) || 0;
        return prev + to_be_added;
    },0)
    console.log(total2);
    $("#sumtotal").val(total2.toFixed(2));
    return total2;
}
//function that gets the amount due(balance left)
function amountDue() {
    var amount =  parseFloat($("#sumtotal").val());
    var paidd =   parseFloat($("#paid").val());
    var balance =  amount - paidd;
    $("#due").val(balance.toFixed(2));
    $("#due2").val(balance.toFixed(2));
    //return total2;
}
//function that updates #uprice and #descript from the data base onchange of the select box
function get_item(elementID){
    $.ajax({
    method:"POST",
    url:"get_price.php",
    data:{item2:$("#item").val()},
    success:function(data){
        alert(data);
        if(data!='0'){
            //$('#descript').val(data);
          $('#uprice').val(data);
        }else{
            alert('Description not available');
        }
    }
});
    $.ajax({
        method:"POST",
        url:"get_item.php",
        data:{item:$("#item").val()},
        success:function(data){
            alert(data);
            if(data!='0'){
               $('#descript').val(data);
            }else{
            alert('Description not available');
            }
        }
    });

}

</SCRIPT>

//My html code

<table id="dataTable" class="form"> <thead> <th style="width:20px"></th> <th>Item</th> <th>Description</th> <th>Unit Price</th> <th>Item Units</th> <th>Sub Total (#)</th> </thead> <tbody> <tr id='row_0'> <td><input style="width:20px" type="checkbox" name="chkbox[]" /> </td> <td> <select required="required" name="item" onchange="get_item('row_0')" id="item" placeholder="Item"> <option value="0"> select an item</option> <?php echo $options;?> </select> </td> <td> <input type="text" required="required" class="small" name="descript" id="descript" placeholder="Description"> </td> <td> <input type="text" required="required" name="uprice[]" oninput="calculate('row_0')" id="uprice" placeholder="unit price"> </td> <td> <input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="0"> </td> <td> <input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" value="0.00" readonly="readonly" style="background-color: white"> </td> </tr> </tbody> </table> <span id="mee"></span> <input type="button" value="Add" onClick="addRow('dataTable')" class="butto" /> <input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/> 
2
Contributors
1
Reply
20
Views
4 Weeks
Discussion Span
Last Post by kinhkha1984
0

Hi,

In function addRow(), you insert this code:

function addRow(dataTable) {
    var table = document.getElementById("dataTable");
    var rowCount = table.rows.length;
    if (rowCount < 4) { // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);
        var colCount = table.rows[1].cells.length;
        row.id = 'row_'+rowCount;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.outerHTML = table.rows[1].cells[i].outerHTML;            
        }
        var listitems= row.getElementsByTagName("input")
        for (i=0; i<listitems.length; i++) {
            listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
        }

        /* new code */
        // change id select
        var listselects= row.getElementsByTagName("select");
        for (i=0; i<listselects.length; i++) {
            listselects[i].setAttribute("onchange", "get_item('"+row.id+"')");
        }
        /* end new code */
    } else {
        alert("Maximum Row Reached.");
    }
}

Good luck!

Edited by happygeek: spam removed

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.