Adding the text area input to a list with jquery
- by amylynn83
I am making a shopping list app. When an item is added to the text input, it should be converted into a list item with a class of "tile" and added to the beginning of the list with a class of ".shopping_item_list". Here is my HTML:
<section>
<h1 class="outline">Shopping List Items</h1>
<ul class="shopping_item_list">
<li class="tile">Flowers<span class="delete">Delete</span></li>
</ul>
</section>
My jQuery:
$("input[name='shopping_item']").change(function() {
var item = $(this).val();
$("<li class='tile'>+ item +</li>").prependTo(".shopping_item_list");
$(".tile").removeClass("middle");
$(".shopping_item_list li:nth-child(3n+2)").addClass("middle");
});
This isn't working, and I can't figure out why. I'm new to jQuery.
Also, I need to add the "delete" span to the list item and am not sure how.
Thanks for any help you can offer!
Edited to add:
Thanks to the feedback here, I was able to make it work with:
$("input[name='shopping_item']").change(function() {
var item = $(this).val();
$("<li class='tile'>" + item + "<span class='delete'>Delete</span>" + " </li>").prependTo(".shopping_item_list");
$(".tile").removeClass("middle");
$(".shopping_item_list li:nth-child(3n+2)").addClass("middle");
});
However, in my jquery, I have functions for the classes "tile" and "delete" that are not working for newly added items.
// hide delete button
$(".delete").hide();
// delete square
$(".tile").hover(function() {
$(this).find(".delete").toggle();
});
$(".tile").on("click", ".delete", function() {
$(this).closest("li.tile").remove();
$(".tile").removeClass("middle");
$(".shopping_item_list li:nth-child(3n+2)").addClass("middle");
});
// cross off list
$(".tile").click(function() {
$(this).toggleClass("deleteAction");
});
The new items, which have these classes applied aren't using these functions at all. Do I need to add the functions below the add item? Does the order in which they appear in my js file matter? Do I need to add some kind of function?