I'm having trouble with a really simple script, consisting of a text box, button, and list of items. Clicking the button adds the text box value to the list. For some reason, though, the text is getting appended as pure text, and not inside of an li element. JSFiddle
<form>
<input type="text" class="form-control" placeholder="Task" id="text_task">
<button type="submit" id="btn_add_task" class="btn btn-primary">Add Task</button>
</form>
<ul id = "list_tasks">
</ul>
JS:
function $(element) {
return document.getElementById(element);
}
var taskSubmit = $('btn_add_task');
var taskBox = $('text_task');
var taskList = $('list_tasks');
taskSubmit.addEventListener('click', function(e) {
e.preventDefault();
var task = taskBox.value.trim();
var newLI = document.createElement('li');
var element = newLI.appendChild(document.createTextNode(task));
taskList.appendChild(element);
taskBox.value = '';
}, false);
I'm having trouble with a really simple script, consisting of a text box, button, and list of items. Clicking the button adds the text box value to the list. For some reason, though, the text is getting appended as pure text, and not inside of an li element. JSFiddle
<form>
<input type="text" class="form-control" placeholder="Task" id="text_task">
<button type="submit" id="btn_add_task" class="btn btn-primary">Add Task</button>
</form>
<ul id = "list_tasks">
</ul>
JS:
function $(element) {
return document.getElementById(element);
}
var taskSubmit = $('btn_add_task');
var taskBox = $('text_task');
var taskList = $('list_tasks');
taskSubmit.addEventListener('click', function(e) {
e.preventDefault();
var task = taskBox.value.trim();
var newLI = document.createElement('li');
var element = newLI.appendChild(document.createTextNode(task));
taskList.appendChild(element);
taskBox.value = '';
}, false);
Share
Improve this question
asked Sep 19, 2014 at 18:23
Tim AychTim Aych
1,3654 gold badges17 silver badges34 bronze badges
1
-
@Teemu because
$()
is typical jQuery selector syntax. – BenM Commented Sep 19, 2014 at 18:27
1 Answer
Reset to default 7It's because you're returning the textNode to element
when you should be appending newLI
var newLI = document.createElement('li');
newLI.appendChild(document.createTextNode(task));
taskList.appendChild(newLI);
FIDDLE