Search code examples
javascriptinputpushdefault-value

Input Value - undefined or not showing up


i am coding To do list app, but javascript code has some errors. so the problem is that when Li shows up it is "undefined" or sometimes even blank space HTML

    <section>
    <div class="list-app">
        <ul id="list">
            <li>Hell</li>
        </ul>
        <div class="bottom">
            <input type="text" name="game"  placeholder="Type Your List">
            <img src="add.png" id="add">
            <img src="trash.jpg" id="remove">

        </div>
    </div>
</section>

and javascript

var remove = document.querySelector('#remove');
var add = document.getElementById('add');
var textPlace = document.querySelector('input');
var listSingle = document.querySelector('LI');
var input = document.getElementsByName('game');
var items = [''];

add.addEventListener('click', function() {
  items.push = [input.value];

document.getElementById('list').innerHTML = '<li>' + items + '</li>';


})

dont mind other code it's just copped version for add button


Solution

  • I think the problem is with the following code. This returns a collection of NodeList (MDN Ref) document.getElementsByName('game')

    that being said, if you need to get value of input, you have to use the following code

    items.push(input[0].value);
    

    However, I think this is not a good practice to use getElementsByName, I would prefer to use getElementById and add id attribute to input element.

    also, if you want to list input value as an individual list item, use the following code.

    document.getElementById('list').innerHTML = items.map(item => '<li>' + item + '</li>');
    

    hope this helps!