Flying SpaceCow
Flying SpaceCow

Reputation: 23

How do I add items to a javascript array and display the array in a html <li>

I'm missing something very basic I know, but I can't seem to find the solution.

I’m having difficulty understanding how html and Javascript elements interact. My code has some of the right content, but I know it's nowhere near correct yet. I'm also not sure if it matters to place the javascript code in the html file itself or if I can keep it in an external js file and call it.

Anyways, I’m trying to create a To Do list. I want to: -Store the items in my ‘list’ array -Display the entirety of the items in an ordered list -Allow a user to add new items to the list (via text input on the index page)

Any guidance would be appreciated

My code:

<body>
<div id="wrapper">
<h3></h3>
    <ol id="unfinished">

    <form name="addToList">
    <li><input type="text" id="newItem"></li>
    </form>

    <li></li>

(And in my js file)

var list = []
var newItem = document.getElementsById("newItem");

Upvotes: 1

Views: 437

Answers (2)

Ragnarokkr
Ragnarokkr

Reputation: 2328

If your goal is to realize a simple way to insert items into a list, I think the @Zim84's solution is good for your needs.

But, if you wanna realize a ToDo list or something similiar, I suggest you to take a look at TodoMVC where it's possibile to find examples about that kind of job (inserting items into lists with two-way binding - i.e. items in sync between list and input data) in plain vanilla Javascript and many others frameworks and libraries.

Upvotes: 2

Zim84
Zim84

Reputation: 3497

What you need is:

  • a 'input' field for the new todo-item
  • a list, for example an 'ol' list to display your items
  • a button that adds the new item to the list
  • an event listener that listens to your button

as an example:

<ol id="listforitems">
    <li>Item that is already there</li>
</ol>
<input type="text" id="newlistitem">
<input type="button" id="buttonfornewitem" value="Add to list">

these are already the first few points. the magic now comes with JS

// event listener that waits for "click" event on the button
document.getElementById('buttonfornewitem').addEventListener('click', function(e) {
    // we create a new element to append it to the list
    var newElement = document.createElement('li');
    // we define the content of the new element to be the value that has been entered in the input-field
    newElement.innerHTML = document.getElementById('newlistitem').value;
    // then we add it to the list
    document.getElementById('listforitems').appendChild(newElement);

    // optional: reset the input field so that you can add another todo-task
    document.getElementById('newlistitem').value = '';
});

Upvotes: 4

Related Questions