Search code examples
javascriptcssarraysfor-loopalignment

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.

HTML

<body>
<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="[email protected]" required /><br>
<label>Age: </label>
<select></select>
</fieldset>

<fieldset id="Programs">
<legend>Programs</legend>
<ul></ul>
</fieldset>
</form>

JavaScript

//************************
//Generate course options list

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

    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
        uList.appendChild(inputs);
    //place label in ul after checkboxes
        uList.appendChild(labels)
        if (i % 2) {
            var breakLine = document.createElement("br");
            uList.appendChild(breakLine);
        }//End if
    }//End for loop
} //End generateCourses function

Here is the full code https://jsfiddle.net/gat4vo9p/2/


Solution

  • I changed your code a bit:

    https://jsfiddle.net/gat4vo9p/7/

    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.