I’m trying to calculate a running total from multiple input fields using JavaScript, but I keep running into an issue where the script can’t find the elements.
The error I’m getting is:
document.getElementById("price_field[" + index + "]") is null
Here’s my current JavaScript function:
function updateGrandTotal(itemCount) {
var index = 1;
var grandTotal = 0;
while(index <= itemCount) {
grandTotal = parseInt(grandTotal) + parseInt(document.getElementById('price_field[' + index + ']').value);
index++;
}
document.getElementById('final_amount').value = parseInt(grandTotal);
}
I’m not sure why the elements aren’t being found. The HTML inputs exist with the correct IDs, but JavaScript seems to think they’re null. Has anyone encountered this before? What am I missing here?
The issue arises because parseInt() encounters null values when getElementById fails to find an element. This situation often occurs due to gaps in your index, such as having price_field[1] and price_field[3] while missing price_field[2], causing the loop to fail at the missing index. To prevent crashes, introduce a null check prior to calling parseInt. You can update your while loop as follows: var element = document.getElementById('price_field[' + index + ']'); if(element && element.value) { grandTotal += parseInt(element.value) || 0; }. This adjustment will allow the loop to skip over any missing elements rather than terminate abruptly. Additionally, consider implementing isNaN checks since parseInt can yield NaN if the input is not valid.
Had this exact problem last month - drove me absolutely nuts for hours. Your script’s running before the DOM elements load. Even though you can see the HTML inputs in the browser inspector, JavaScript tries to access them before they’re actually available. Wrap your function call in window.onload or document.addEventListener(‘DOMContentLoaded’, function() {}). Also add null checks in your while loop - check if the element exists before accessing its value. This stops the script from breaking when it hits a missing element and helps you figure out which index is causing issues.
Check your HTML IDs first - hidden characters or extra spaces will break things. Try querySelector instead: document.querySelector('[id="price_field[' + index + ']"]'). getElementById gets weird with brackets sometimes.