Reputation:
I am trying to create a table using the arrays for a program outline for school. How do I make the second array (num) line up next the course title. Right now it is just stacking below them in the same column....
<script>
var titl = ["Oral Communication","Applications/Concepts","SQL Programming","HTML and Dreamweaver","Javascript","Flash","XML","Cascading Style Sheets","XSL","ASP.NET","PHP/MySQL","Windows Operating Systems","Digital Imaging with Photoshop","Web Development Internship"];
var num = ["ENG171","CIT110","CIT236","CMT111","CMT113","CMT115","CMT117","CMT125","CMT211-see note*","CMT215","CMT241","CIT268","VMA105","CMT299"];
document.write('<table>')
document.write('<tr><th>Web Development Concentration Courses</th></tr>');
for (var i = 0; i < titl.length; i++)
{
document.write('<tr><td>' + titl[i] + '</td></tr>');
}
for (var j = 0; j < num.length; j++)
{
document.write('<tr><td>' + num[j] + '</td></tr>');
}
document.write('</table>');
</script>
Upvotes: 0
Views: 37
Reputation: 7676
Combine the two loops
for (var i = 0, j= 0; i < titl.length || j < num.length; i++,j++)
{
document.write('<tr><td>' + titl[i] + '</td> <td>' + num[i] + '</td></tr>');
}
Upvotes: 0
Reputation: 167162
You cannot split things when you are constructing HTML. Also, please do not use document.write
, as it is dangerous.
Also, the main solution is to combine the loops. I am doing it by checking the lengths of the two arrays to be same:
var titl = ["Oral Communication", "Applications/Concepts", "SQL Programming", "HTML and Dreamweaver", "Javascript", "Flash", "XML", "Cascading Style Sheets", "XSL", "ASP.NET", "PHP/MySQL", "Windows Operating Systems", "Digital Imaging with Photoshop", "Web Development Internship"];
var num = ["ENG171", "CIT110", "CIT236", "CMT111", "CMT113", "CMT115", "CMT117", "CMT125", "CMT211-see note*", "CMT215", "CMT241", "CIT268", "VMA105", "CMT299"];
var finalHTML = '<table>';
finalHTML += '<tr><th>Web Development Concentration Courses</th></tr>';
if (titl.length == num.length)
for (var i = 0; i < titl.length; i++) {
finalHTML += '<tr><td>' + titl[i] + '</td><td>' + num[i] + '</td></tr>';
}
finalHTML += '</table>';
document.getElementById("container").innerHTML = finalHTML;
<div id="container"></div>
Preview
Also, giving the <th>
a colspan="2"
will give you better results:
finalHTML += '<tr><th colspan="2">Web Development Concentration Courses</th></tr>';
Upvotes: 2