parseFloat returning NaN

I hate to ask yet another newbie question, but I’ve been searching for at least an hour on how to resolve a problem and I haven’t had any success. I’m trying to get a grand total from several subtotals. The parseFloat function is returning NaN. Even after going over several articles: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat, https://www.w3schools.com/jsref/jsref_parsefloat.asp, https://stackoverflow.com/questions/7264752/javascript-returning-nan I’m still foggy as to what I’m doing wrong. Any insight you all might offer would be much appreciated. Also, one of the commenters in Stack Overflow post suggested that floats should not be used in calculations, but instead use “cents”. I’m not sure what is meant by this. Many thanks in advance for your time.

Also, here is my first attempt at a jsfiddle: https://jsfiddle.net/jcarlisle/nLyzabwL/ though it is apparently not working the same way as it is in my browser.


#dataTable{
    counter-reset: tableCount;
}

#dataTable tr {
    counter-increment: row;
}

#dataTable td:first-child::before {
    content: counter(row);
}

#lineNum{
    width: 108px;
    background-color:white;
}

#contractNum{
    width: 105px;
    background-color:white;
}

#descr{
    width: 508px;
    background-color:white;
}

#qty{
    width: 68px;
    background-color:white;
}
#priceEach{
    width: 75px;
    background-color:white;
}
#priceTotal{
    width: 158px;
    background-color:white;
}



#tdLineNum{
    width: 100px;
    text-align: center;
    background-color:white;
}

#tdContractNum{
    width: 100px;
}

#tdDesc{
    width: 500px;
}

#tdQty{
    width: 60px;
}
#tdPriceEach{
    width: 70px;
}
#tdPriceTotal{
    width: 150px;
}

<form>

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

            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());
        });
        alert(sum);
            $("#grandTotal").val(sum);
//        $('#grandTotal').outerHTML;
//            gTotal.value = sum;

        }
    </script>

When you enter data into the form, the browser console tells you what is going wrong.

1 Like

This line is the one causing you trouble:

sum += parseFloat($(this).text());

You’re looping over <input> elements, so you’ll need to call .val() to get the value.

1 Like

@fretburner Bingo!! That was IT EXACTLY. Thank you so much!!! As far best practice, does it look like I’m using parseFloat correctly? Seems like Felix Kling on the Stack Overflow article thought that computations should not be made in floats, but rather in cents. You can see that in my calculate(elementID) function, I’m using the toFixed method to round to 2 decimals. That seems to be working correctly.

Also, I’m trying to implement “delete row” functionality, however the deleteRow function does not seem to be working correctly. I got that code from here: https://stackoverflow.com/questions/31470273/perform-calculations-on-dynamically-added-rows and it would appear that I need to include a checkbox for each line item that enables it to be deleted. Thoughts?

@Paul_Wilkins many thanks for your insight. I will try to use the browser console.

edit: @Paul_Wilkins Okay, so I viewed the console using the original code > sum+=parseFloat($(this).text()) and there was no error thrown in the console. However, when I tried to use $("#grandTotal").val(sum).toFixed(2); then I got an error “TypeError: $(…).val(…).toFixed is not a function”

edit: I have subsequently changed it to $("#grandTotal").val(sum.toFixed(2)); and the error has gone away, but that still doesn’t explain why the original erroneous code threw no error. :frowning:

BTW, thank you for your patience in helping me. You’ve probably guessed that I’m still very new to web development.

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