Why is my code returning a comma after every element?

716 views Asked by At

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> -->

3

There are 3 answers

6
Mureinik On BEST ANSWER

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;
}
2
Lawrence Cherone On

Change:

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

to (or similar)

document.getElementById("output").innerHTML = `
Student List:
<ol>
 <li>${roster.join('</li><li>')}</li>
</ol>`

the cause for the , is "Student List" + roster because its an array to string i.e roster.toString()


Expanded example:

let roster = ['Steve', 'Bill']

// wrong
console.log('toString:', roster.toString())

// wrong
document.getElementById("output").innerHTML = 'Wrong<br>'
document.getElementById("output").innerHTML += "Student List" + roster;

// right (using join, there is various other ways to build output)
document.getElementById("output").innerHTML += '<br><hr>Right<br>'
document.getElementById("output").innerHTML += `
Student List:
<ol>
 <li>${roster.join('</li><li>')}</li>
</ol>
`
<div id="output"></div>

0
max On

This is an alternate approaching that creates an ordered list inside a placeholder element. Instead of using an array it just uses the document as state.

And instead of using sting concatenation it uses a programatical approach to creating and appending new elements to the document.

// Creates an `<ol>` element in the target node if none can be found
// or returns an existing list
function createList(target) {
  let list = output.querySelector('ol') || document.createElement("ol");
  // append the element if its a newly created element
  if (!list.parentNode) target.appendChild(list);
  return list;
}

// Appends a <li> element to the list with the text provided by the name argument
function addStudent(name, list){
  let student = document.createElement('li');
  student.appendChild(document.createTextNode(name));
  list.appendChild(student);
  return student;
};

// This adds an event listener which catches the 
// submit event as it bubbles up to the top of the dom.
// Since we are not attaching the handler directly 
// to the element we don't have to wait for the document to be ready
document.addEventListener('submit', function(event){
  let form = event.target;
  let output = document.getElementById('output');
  // bail early if this isn't the right form or there is no output
  if (form.id !== 'theForm' || !output) return; 
  event.preventDefault(); // prevents the normal form submission
  addStudent(form["student"].value, createList(output));
});
<div id="output"></div>

<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>

The reason I chose to create the element dynamically is that an list element without any items is invalid HTML.