WordWizard WordWizard - 1 year ago 52
CSS Question

How to equally align two vertical columns created using a loop, an array, and appending childs in JavaScript (or CSS)?

What I am trying to do is generate HTML with JavaScript using loops and arrays. What I am currently trying (and having issue with) is my second column. I have an array of courses to that are placed into input checkboxes followed by labels. From there I used an if statement to add breaks after every second iteration to create my columns. My problem is getting the second column to align vertically. I wanted to do it using just JS and not CSS, but I am open to either.

Since my question has multiple parts, I wasn't sure what keywords to use to use to narrow my search for aligning columns using .createElement in a loop to create 2 columns and align them vertically in JavaScript, so if this has been answered in another place, feel free to drop a line.

Here is the relevent code.


<section id="wrapper">
<form action="POST" novalidate="novalidate">
<fieldset id="contactInfo">
<legend>Contact Info</legend>
<label>Name: </label>
<input type="text" placeholder="John" required autofocus /><br>
<label>Email: </label>
<input type="email" name="email" placeholder="galacticDonut@yahoo.com" required /><br>
<label>Age: </label>

<fieldset id="Programs">


//Generate course options list

function generateCourses() {
var courseOptions = ["CSCI","CSIA","DBMS","INFA","ITSP","NETI","SDEV","SVAD"]

var uList = document.getElementsByTagName("ul")[0];

for (var i=0; i<courseOptions.length; i++) {
//Create inputs
var labels = document.createElement("label");
labels.innerHTML = courseOptions[i];

var inputs = document.createElement("input");
inputs.setAttribute("type", "checkbox");
//Set input value
inputs.value = courseOptions[i];
//Set input text
inputs.text = courseOptions[i];
//Put input in UL
//place label in ul after checkboxes
if (i % 2) {
var breakLine = document.createElement("br");
}//End if
}//End for loop
} //End generateCourses function

Here is the full code

Answer Source

I changed your code a bit:


Added an li element inside ul. Each li behaves like a table row.

ul {
  list-style: none;
  position: relative;

li {
  display: table;
  width: 100%;
  height: 30px;
  vertical-align: middle;
li > span {
  display: table-cell;
  width: 50%;

Also added <label for attribute. So clicking on the label will mark/unmark the checkbox, as well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download