javascriptarraysnumbered-list

Why is my code returning a comma after every element?


I am trying to return the array with index in front of each element, and also remove the commas after every element. I was able to return each element to a new line with the push() but still can't get the numbered list. I've tried using <li> and <ol> in my js where the <div> is as well. What am I missing here?

// TODO keep the student list state in a global list

var roster = new Array("");

function addStudent() {
    // TODO lookup the user entered text

    var newStudent = document.getElementById("student").value;

    // TODO store the new student name in global list

    roster.push("<div>" + newStudent + "</div>");

    // TODO render the entire list into the output div

    roster.innerHTML = roster.join('');
    document.getElementById("output").innerHTML = "Student List" + roster;

    return false;
} 

function init() {
    // TODO register the onsubmit for 'theForm' to use addStudent

    if (document && document.getElementById) {
        document.getElementById('theForm').onsubmit = addStudent;
    }
} 
window.onload = init;
    <form action="#" method="post" id="theForm" novalidate>
        <fieldset>
            <legend>Enter a student name to add to the roster</legend>
            <div><label for="student">Student Name</label><input type="text" name="student" id="student"></div>
            <input type="submit" value="Add to Roster" id="submit">
            <div id="output"></div>
        </fieldset>
    </form>
    <!-- <script src="js/students.js"></script> -->


Solution

  • Instead of relying on innerHtml, you should just create a string from the roster. In order to convert it to an ordered list, you should surround the resulting string with <ol> and </ol>, and add a <li> tag to each element. Note that the roster array should be initialized to an empty array, not an array containing "":

    var roster = new Array();
    
    function addStudent() {
        // TODO lookup the user entered text
    
        var newStudent = document.getElementById("student").value;
    
        // TODO store the new student name in global list
    
        roster.push("<div>" + newStudent + "</div>");
    
        // TODO render the entire list into the output div
    
        rosterStr = '<ol>' + roster.map(r => `<li>${r}</li>`).join('') + '</ol>';
        document.getElementById("output").innerHTML = "Student List" + rosterStr;
    
        return false;
    }