2

I'm trying to make a list from info the user enters.

   var todoArray = new Array();

document.getElementById("addButton").onclick = function(){

    var temp = document.getElementById("inputBox").value;
    var appendTemp = "<li><input type=\"checkbox\">" + temp + "</li>";

    todoArray.push(appendTemp);

    document.getElementById("todoListUL").innerHTML = todoArray;

    console.log(todoArray);

}

But when the list times show up, they all have a comma between them, JSFiddle link for imagery here: JSFiddle

Why are they separated by this comma and how do I remove it?

2
  • Because that's how an array's toString() is implicitly called when you try to make an array a string - in document.getElementById("todoListUL").innerHTML = todoArray; Commented May 7, 2018 at 12:44
  • todoArray.join('[use a character here or not]') Commented May 7, 2018 at 12:44

2 Answers 2

4

When you assign any value to the .innerHTML property of an element, the value is implicitly converted to a string and then parsed as HTML. The default way that an array is converted to a string is via the .join() method, and the default array separator is a comma.

If you don't want anything, you can just call .join() yourself:

document.getElementById("todoListUL").innerHTML = todoArray.join("");
Sign up to request clarification or add additional context in comments.

Comments

1

The issue is in this line:

document.getElementById("todoListUL").innerHTML = todoArray;

because the right member is converted to string and it is invoked internally the join method for todoArray array and default delimiter is comma.

Change it to

document.getElementById("todoListUL").innerHTML = todoArray.join("");

1 Comment

Thank you! This fixed it and helped me understand the issue. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.