0

Hello everyone..

I'm developing a calorie counter with a <select> tag as my list of foods. It currently calculates the number of servings, calories per serving as well as the daily caloric intake.

My problem is I implemented a "delete row" function to delete a food in case a user has inputted it by mistake, the problem is it does not deduct correctly from the total..

I think the problem is in the loop. anyway, here is the code:

function AddToList()
{
	 var passingvalue = document.serving.foods.value
	 DCI = document.serving.DCI.value
	 var splitArr = passingvalue.split("|");
	 var servingSize = splitArr[0];
	 var Calories = splitArr[1];
	 var foodChoice = document.serving.foods.options[document.serving.foods.selectedIndex].text;
	 
	var newRow = document.getElementById("InTake").insertRow();

	var oCell = newRow.insertCell();
	var element1 = document.createElement("input");         
    element1.type = "checkbox";          
	oCell.appendChild(element1); 
	
	oCell = newRow.insertCell();
	oCell.innerHTML = foodChoice;
	
	oCell = newRow.insertCell();
	oCell.innerHTML = servingSize

	oCell = newRow.insertCell();
	oCell.innerHTML = document.getElementById('noserving').value;
	
	oCell = newRow.insertCell();
	oCell.innerHTML = Calories
	
	oCell = newRow.insertCell();
	var servingNo = document.getElementById("noserving").value
	var total = Calories * servingNo
	oCell.innerHTML = total
	
	UsedCalories = UsedCalories + total
	remainingCalories = DCI - UsedCalories
	document.getElementById("CalTotal").innerHTML = UsedCalories
	document.getElementById("CalRem").innerHTML = remainingCalories
}


function SaveData()

{

	createRequest();
  var url = "SaveData.asp?Rem=" + escape(remainingCalories) + "&DCI=" + escape(DCI)+"&RandomKey=" + Math.random() * Date.parse(new Date());
  request.open("GET", url, true);
  request.onreadystatechange = ShowRemaining;
  request.send(null);
  alert("data sent");
}


function ShowRemaining()
{
     var fullString;
     if (request.readyState == 4) 
     {
	
       if (request.status == 200) 
       {
	    alert("working");
			fullString=request.responseText;
			alert(fullString);
       }
     }


}

the delete row function

function deleteRow(InTake) {     
		try {        
		 var table = document.getElementById(InTake); 
		 var currentTotal = document.getElementById('UsedCalories');
		 var rowCount = table.rows.length;  
			var dt = 0;
		 for(var i=0; i<rowCount; i++){         
		 var row = table.rows[i];           
		 var chkbox = row.cells[0].childNodes[0];
		 var ns = row.cells[3].childNodes[0].nodeValue;
		 var cps = row.cells[4].childNodes[0].nodeValue;
		  dt = ns * cps;
		 
		 if(chkbox != null && chkbox.checked == true){    
		 table.deleteRow(i);                  
		 rowCount--;                
		 i--;
		 }        
			}
			alert(dt);
		  }
		  catch(e)
				{        
		  alert(e);      
					}	
					alert('yay');
						var updated = UsedCalories - dt;
						alert(updated);
						 document.getElementById("CalTotal").innerHTML = updated;
						  var updatedRem = remainingCalories + dt;
						 document.getElementById("CalRem").innerHTML = updatedRem;
						
						
											

		  }
2
Contributors
5
Replies
6
Views
6 Years
Discussion Span
Last Post by MartinRinehart
0

I forgot to input the HTML code as well, just for reference

Number of servings: <input type="text" name="noserving" id="noserving"/><br />
  <!--<input type="Submit" value="Add" />-->
  <input type="button" onclick="AddToList()" value="Add">
  
  <input type="hidden" name = "entry" id="entry"></input> 
  <br>
<div id="Calor"></div>
<div id="ConsumedSoFar"></div>  
</form> 

<table id="InTake" width="60%" border=1>
<tr>

	<td>Selector</td>
	<td>Food Type</td>
	<td>Serving Size </td>
	<td>No.of servings</td>
	<td>Calories per serving </td>
	<td>Total Calories </td>
</tr>
<table id="InTake" width="60%" border=1>
<tr>
	<td colspan="2">Total</td>
	<td id="CalTotal"></td>
</tr>
<tr>
	<td colspan="2">Remaining</td>
	<td id="CalRem"></td>
</tr>
</table>
<!--button type="button" onClick="calculateServing(),showCalories(this)" >Enter</button>-->
 
<button type="button" onClick="SaveData()" >Enter</button>
<INPUT type="button" value="Delete Entry" onclick="deleteRow('Intake');" />
0

Design issue. You can get code like this to work, but it's devilish hard and will probably find another bug for you tomorrow.

You are trying to process content in a loop while also modifying the content. Do one job, then the other.

1) process all rows. (Get the total, get the calories from the food you don't want.)
2) modify the table (in this case, deleting the row you don't want)

Do not worry about wasting some CPU processing rows twice. Your viewer has lots of CPU cycles. Performance problems are easy to solve if you wait for them to actually appear. (And if you have a performance issue here, it won't be from processing the rows twice.)

By the by, those first <td>s where you have the column headings: make them <th>s. You'll probably like the look.

0

Thanks Martin, I really like the look of the new table with it highlighted as <th>.

But regarding your suggestion about looping through the table and calculating the total, that works just fine, but I cant seem to get the total value updated after the row is deleted.. thats my problem

I guess because a cell's content is in innerHTML and the total is a number, should I cast it by using .toString() then inputting it in the cell?

0

'should I cast it by using toSting() ...'

Java programmer?

In JS, the 'cast' is as simple as "'' + number". The '+' operator is overloaded. It will 'toString()' either operand if one is a string.

Host objects (all DOM objects in a browser) are outside JS's ECMA 262 spec. As a guess, most will 'toString()' anything added to innerHTML, for you. Just looking at the table should tell you.

Before deleting the row, calculate the total and double-check with an alert() or console.log. Then delete the row and update the total value widget.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.