kmgiffin kmgiffin - 4 months ago 8
Javascript Question

The values in my array will not render in the DOM

The array shows up when I console.log it, but when i try anything else (alert with array and key, or just appending it) only undefined shows up. In this case, what actually shows up on my screen is: checkbox undefined button

<body>
<input id="text-field-input" type="text" placeholder="what do you have to do?"/>
<button id="submit">submit</button>
<ul id="list-section">
</ul>




var toDoList = [];

function addInputToList(todoinput, checkchecked) {
toDoList.push({todo : todoinput, checked : checkchecked});
};

function renderToDos() {
$('#list-section').append('<input type="checkbox">' + toDoList.todo + ' ' + '<button>x</button>');
};

$('#submit').on('click', function() {
var textFieldInput = $('#text-field-input').val().toLowerCase();

addInputToList(textFieldInput, false);
renderToDos();
});

Answer

In your code you are trying access an object property on array which does not have such properties( i.e todo). That's why you are getting undefined.

Perhaps you want to achieve this -

var toDoList = [];

function addInputToList(todoinput, checkchecked) {
    toDoList.push({todo : todoinput, checked : checkchecked});
};

function renderToDos() {
  var count = toDoList.length;
  if(count > 0){
    var addedTodo = toDoList[count-1]
       $('#list-section').append('<input type="checkbox">' + addedTodo.todo + ' ' + '<button>x</button>');
    }
 
};

$('#submit').on('click', function() {
    var textFieldInput = $('#text-field-input').val().toLowerCase();

    addInputToList(textFieldInput, false);
    renderToDos();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="text-field-input" type="text" placeholder="what do you have to do?"/>
<button id="submit">submit</button>
<ul id="list-section">
</ul>

Comments