Hi Here I have an html Table and with JavaScript I’m looping through and doing math. for each row the first number is added to the second number and if it doesn’t add up to the third number a fourth number is added and highlighted. This works great for me.
I need to create a method (checkCalculate) that receives the child node as a parameter with no return.
my problem is im not sure where to place it?
if I add a method like CheckCalculate: function(‘’){ } where do I put it to add a method into my code and is that how I write a method? I keep trying different places and it keeps breaking my code?
Im supposed to add a method and inside the method it would receive the child node as a parameter with no return value. Im not sure if im adding the proper code to add the method or how to properly call the method to have it display properly?
the assignment is asking to have a for counter loop through the calculation array. The calculation childNode contains the data i need.
then im supposed to Create a method CheckCalculate that receives the child node as a parameter with no return value. Build the calculation same as previously, The first number is in position 1, the second in position 3, and the expected result in position 5. The textContent of the child node has the value. Remember that page data is text and has to be converted to a number. Add the number in the first field to the number in the second field. If the calculation as described in the html table is incorrect set the background color of the row (the array value) to #FA8072 and dynamically add another cell containing the correct result only to the failed calculation.
Because the code in the for loop uses the variable calculation for the node, it helps to keep things simple and use calculation as a function parameter.
After the code is moved in to the function and things are made to still work, that’s when it’s a good time to think about renaming the function parameter to a potentially better name.
<script type="text/javascript">
var calculations = document.getElementsByClassName("Calculation");
var numberOfCalculations = calculations.length;
for (var counter = 0; counter < numberOfCalculations; counter++) {
checkCalculation(calculations[counter]);
}
var calculation = calculations[counter]; //get the calculation
var firstNumber = Number(calculation.childNodes[1].textContent);
var secondNumber = Number(calculation.childNodes[3].textContent);
var expectedResult =Number(calculation.childNodes[5].textContent);
//}
var result = firstNumber + secondNumber; //add the first 2 numbers together
function checkCalculations(calculation){
if (result == expectedResult) //compare our result with the stored result
{
//we're equal
}
else
{
//we're not equal
calculation.style.backgroundColor = "#FA8072";
var resultCell = document.createElement("td");
calculation.appendChild(resultCell);
resultCell.appendChild(document.createTextNode(result));
}
}
</script>