Forum Moderators: open

Message Too Old, No Replies

JavaScript Table Problem

JavaScript Table Problem

         

egarcia1

5:29 pm on Jan 29, 2008 (gmt 0)

10+ Year Member



I want to produce a table with 3 columns using a for loop and have a function run a check within that function to see is the Fahrenheit value is below a certain temp. If it is then in a different cell generate a string of "feels cool".

I have the following code:

<body>
<table>
<tr><td>CELSIUS</td><td colspan="2">FAHRENHEIT</td></tr>
<script language="javascript">

for ( celcius = 0; celcius <= 20; celcius = celcius+1)

{
document.write("<tr><td>"+celcius+"</td><td id='temp'>"
+((celcius*9/5)+32)+"</td><td id='feel'>1</td></tr>");
}
if(document.getElementById('temp').innerHTML < 40)
{
document.getElementById('feel').innerHTML = "Feels Cool";
}
</script>
</table>
</body>
</html>

Fotiman

5:51 pm on Jan 29, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here's what I'd change:

1. Specify a <thead> in your table for the headings.
2. Use <th> for your heading captions.
3. Instead of celcius = celcius + 1, use celcius++
4. ID values must be unique, but you were reusing 'temp' and 'feel' in each row. As it turns out, you don't need the ids.
5. There's no need to do a getElementById at all if you're going to use document.write. Note, your example is dependent on JavaScript, so anyone with JavaScript disabled will not see any values. But I'm assuming this is for educational purposes only. Here's my changes:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title></title>
</head>
<body>
<table>
<thead>
<tr>
<th>CELSIUS</th>
<th colspan="2">FAHRENHEIT</th>
</tr>
</thead>
<tbody>
<script type="text/javascript">
for (var celcius = 0; celcius <= 20; celcius++) {
var fahrenheit = (celcius * 9 / 5) + 32;
var row = "<tr>";
row += "<td>" + celcius + "</td>";
row += "<td>" + fahrenheit + "</td>";
row += "<td>" + (fahrenheit < 40? "Feels Cool" : "") + "</td>";
row += "</tr>";
document.write(row);
}
</script>
</tbody>
</table>
</body>
</html>

egarcia1

6:05 pm on Jan 29, 2008 (gmt 0)

10+ Year Member



Thank You. I needed help on this immediately and your solution helps immensely. I will use this as a good educational example.
I appreciate your help:)

But what if I want to add a different String value of "feels cold!" if values are say, between 30 and 40?