Reputation: 45
So I've created a simple shopping list / to-do app. It's nearly complete, except for one nagging problem: .text()
keeps returning [object Object]
instead of the input captured.
I don't understand what I'm doing wrong. To show what I'm talking about, I included my JS script:
$(document).ready(function() {
addItem();
deleteAction();
doneAction();
});
function addItem() {
$("button").click(function() {
var value = $(".input-form").val();
$("ul").append('<li> <span class=\"item-name\">'+value+'</span><span class=\"done\"> done</span><span class=\"delete\"> delete</span></li>');
$(".input-form").val('');
});
}
function deleteAction() {
$(".ul-list").on("click", ".delete", function() {
// alert("Delete event fired.");
$(this).closest("li").remove();
});
}
function doneAction() {
$(".ul-list").on("click", ".done", function() {
// alert("Done event fired.")
$(this).closest("li").toggleClass("strike");
});
}
Here's my full code on CodePen: http://codepen.io/barackobama/pen/qOrKBp
Upvotes: 2
Views: 1542
Reputation: 1001
An answer taking into account you might want to use more than one form-entry parsing the whole formcontent into a key-value-pair-list for easy access onto it.
function addItem() {
$("button").click(function() {
var data = $('.input-form').serializeArray().reduce(function(obj,item) {
obj[item.name] = item.value;
return obj;
}, {});
$("ul").append('<li> <span class=\"name\"></span>'+data['additem']+
'<span class=\"done\"> done</span><span class=\"delete\"> delete</span></li>');
$(".input-form").val('');
});
}
Upvotes: 0
Reputation: 1
.name
not appear defined , appended to DOM
when .text()
called at $(".name").text(value)
within string argument to .append()
?
Try setting value
within string argument to .append()
using +
operator e.g, <span class=\"name\">'+value
; moving value
variable declaration within click
event for it to be defined, set at event ; js
at initial codepen set value
when addItem()
initially called at .ready()
, when no value yet set by user
function addItem() {
$("button").click(function() {
var value = $(".input-form").val();
$("ul").append('<li> <span class=\"name\">'+value
+'</span><span class=\"done\"> done</span>'
+'<span class=\"delete\"> delete</span></li>');
$(".input-form").val('');
});
}
codepen http://codepen.io/anon/pen/NGpBBX
Upvotes: 1