JavaScript function to delete a row

My JavaScript function to delete a row is not working well and I understand why. The reason is, when rows are deleted, the remaining rows retain their row id which then skews the row ids of any rows that are added subsequently (I see this in the Inspector/DOM). I need to modify my deleteRow function to also re-initialize each remaining row id, so that subsequently added rows are unique. Hopefully this makes sense and I will look into this further. If anyone wishes to contribute, your help is much appreciated. Kind regards, Jonathan

<form>
<fieldset>
                <legend>Items:</legend>

                <input type="button" value="Add" onClick="addRow('dataTable', 'grandTotal')" />
                <input type="button" value="Remove" onClick="deleteRow('dataTable')" />
                <table>
                <tr id="colHeadings">
                    <th id="lineNum">Line#</th>
                    <th id="contractNum">Contract#</th>
                    <th id="descr">Description</th>
                    <th id="qty">Qty</th>
                    <th id="priceEach">Each</th>
                    <th id="priceTotal">Line item total:</th>
                </tr>
                </table>
                <table id="dataTable" class="form" border="1">
                    <tbody>
                    <tr id='row_0'>
                        <p>
                        <td id="tdLineNum">
<!--                            <input type="text" id="tdLineNum"  required="required" name="lineNum" readonly value="1">-->
                        </td>
                        <td>
                            <input type="checkbox">
                        </td>
                        <td>
                            <input type="text" id="tdContractNum" required="required" name="contractNum">
                        </td>
                        <td>
                            <input type="text" id="tdDesc" required="required" name="desc">
                        </td>
                        <td>
                            <input type="text" id="tdQty" required="required" name="qty" oninput="calculate('row_0')">
                        </td>
                        <td>
                            <input type="text" id="tdPriceEach" required="required" name="price" oninput="calculate('row_0')">
                        </td>
                        <td>
                            <input type="text" class="tdPriceTotal" required="required" name="total" onkeyup="calcGrandTot()">
                        </td>
                        </p>
                    </tr>
                    </tbody>
                    <table>
                    </table>
                    <tbody>
                    <tr id="grandTotalRow">
                        <td>
                            <label for="grandTotal">Grand Total: $</label>
                            <input type="text" id="grandTotal">
                        </td>
                    </tr>
                    </tbody>
                </table>

            </fieldset>
</form>

   <script type="text/javascript">
//            var initialLineNum = 2;
//            var runningTotal = 0;
        function addRow(tableID, grandTot) {
//            alert("in addRow");

//           get a reference to the table
            var table = document.getElementById(tableID);

//              HTMLTableElement.rows read-only property returns a live HTMLCollection of all the rows in the table.
// The rows included in the associated <thead>, ,<tfoot> and <tbody> elements. Although the property is read-only,
// the retuned object is live and allows th modification of its content.
            var rowCount = table.rows.length;
            if (rowCount < 100) { // limit the user from creating fields more than your limits

//                Insert a row in the table at row index(rowCount) and return a reference to the row
                var row = table.insertRow(rowCount);

//                alert(rowCount);
                var colCount = table.rows[0].cells.length;
                row.id = 'row_' + rowCount;

                for (var i = 0; i < colCount; i++) {

//                    Insert a cell in the row
                    var newcell = row.insertCell(i);
                    newcell.outerHTML = table.rows[0].cells[i].outerHTML;
                }
                var listitems = row.getElementsByTagName("input");


                for (i = 0; i < listitems.length; i++) {
//                alert("hello");


                        listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");

                }

            } else {
                alert("Maximum 100 items per purchase order.");

            }
//            initialLineNum++;
        }


        function deleteRow(tableID) {
//            alert("in deleteRow");
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            for (var i = 0; i < rowCount; i++) {
//            alert(rowCount);
                var row = table.rows[i];
//            alert(document.getElementById("dataTable").rows[0].innerHTML);
                var chkbox = row.cells[1].childNodes[1];
                if (chkbox !== null && chkbox.checked === true) {
//            alert(chkbox);
                    if (rowCount <= 1) { // limit the user from removing all the fields
                        alert("Cannot Remove all the Passenger.");
                        break;
                    }
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }
            }

            // need to re initialize the row values here
        }

            function calculate(elementID) {
                var mainRow = document.getElementById(elementID);
                var myBox1 = mainRow.querySelectorAll('[name=qty]')[0].value;
                var myBox2 = mainRow.querySelectorAll('[name=price]')[0].value;
                var total = mainRow.querySelectorAll('[name=total]')[0];
                var myResult1 = myBox1 * myBox2;
                total.value = myResult1.toFixed(2);

            }


    </script>

    <script>

        function calcGrandTot() {
//        alert("in calcGrandTotal");
        var sum = 0.0;
        $('.tdPriceTotal').each(function() {
//            sum += parseFloat($(this).text());

            sum += parseFloat($(this).val());
        });
//        alert(sum);
            $("#grandTotal").val(sum.toFixed(2));
//            $("#grandTotal").val(sum);
//        $('#grandTotal').outerHTML;
//            gTotal.value = sum;

        }
    </script>

Got it!!!

The final deleetRow looks like this:

        function deleteRow(tableID) {
//            alert("in deleteRow");
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            for (var i = 0; i < rowCount; i++) {
//            alert(rowCount);
                var row = table.rows[i];
//            alert(document.getElementById("dataTable").rows[0].innerHTML);
                var chkbox = row.cells[1].childNodes[1];
                if (chkbox !== null && chkbox.checked === true) {
//            alert(chkbox);
                    if (rowCount <= 1) { // limit the user from removing all the fields
                        alert("Cannot Remove all the Passenger.");
                        break;
                    }
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }
            }
            // need to re initialize the row values here
            var tableRows = table.getElementsByTagName("tr");
//console.log(tableRows);
            for (var j = 0; j < rowCount; j++){
            row.id = 'row_' + j;

                tableRows[j].setAttribute("id", "row_" + j);



            var calcFields = row.getElementsByTagName("input");

                for (k = 0; k < calcFields.length; k++) {
//                alert("hello");



                calcFields[k].setAttribute("oninput", "calculate('" + row.id + "')");
                }

            }
        }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.