-2

I want to thank you guys for your response and assistance rendered so far, i am greatful but please i wouldn't mind if you don't get tired on me. Thanks.

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"/>
  • can you please explain your question in detail ? – ashish kumar Jul 17 '18 at 10:51
  • I think all you need to do is to refer : [Click This](https://stackoverflow.com/questions/13190840/input-text-value-based-on-select-option-value-loaded-dynamically-from-sql-db) – Jitendra Ahuja Jul 17 '18 at 10:58
  • _“Most of the examples I have seen aren't working for me.”_ - then go learn the necessary basics to _make_ them work; or at least give us a _proper_ problem description including what you tried and researched so far - see [ask]. – CBroe Jul 17 '18 at 11:58

2 Answers2

0

Already mentoined here, but still: How to submit form on change of dropdown list? . When user submits form, use php fetch from databse, with isset($_POST['name'])

Kristaps
  • 11
  • 4
  • Need to describe what actually needs to be done, so that its always referencible. You can add link for details separately. – NitinSingh Jul 17 '18 at 11:06
0

I was able to fix it with making the some changes in my get_item() javascript function

function get_item(dropDown){
 $.ajax({
    method:"POST",
    url:"get_item.php",
    data:{item:dropDown.value},
    success:function(data){
        alert(data);
        if(data!='0'){
           $($(dropDown).parents('tr')[0]).find('input#descript').val(data);
            //$('#uprice').val(data);
        }else{
            alert('Description not available');
        }
    }
});
}

thanks everyone.