Hello I'm taking an intro javascript class an one of the last assignments is to write a web application to add items to a list using a form text input and button, and allow the user to delete an item from the list by clicking on it.
Now I got all of the code working, except for when the item is displayed on the HTML is comes up as undefined.
Please help
<!doctype html>
<html lang="en">
<head>
<title> Add and delete items Objective </title>
<meta charset="utf-8">
<style>
p {
font-style: italic;
}
li:hover {
cursor: pointer;
}
</style>
<script>
/* create constructor to display the properties, in this case there's only one */
function Item(name) {
this.title = name;
/*this will print it intp the page */
this.print = function() {
var s = "Item: " + this.name;
return s;
}
}
/* empty array where the items will be saved and displayed into the page */
var itemList = [];
window.onload = init;
function init() {
var submitButton = document.getElementById("submitButton");
submitButton.onclick = getItemData;
// add click handler for element created in javascript
var itemList = document.getElementById("itemList");
itemList.onclick = deleteItem;
}
/* form collection for the item
when i enter an item it shows up as undefined in the html */
function getItemData() {
var itemInput = document.getElementById("item");
var item = itemInput.value;
if (item == null || item == "") {
alert("Please enter an item.");
return;
}
/* if something is entered then it is pushed and saved into the itemList */
else {
var items = new Item(name);
itemList.push(items);
addItemToList(items);
}
}
/* this creates the new elements and displays them into the page once they are
saved into the itemList */
function addItemToList(items) {
var itemList = document.getElementById("itemList");
var li = document.createElement("li");
li.innerHTML = items.print();
itemList.appendChild(li);
}
/* this deletes the items from the page */
function deleteItem() {
var li = document.getElementById("itemList");
if (li.firstChild) {
li.removeChild(li.firstChild);
}
}
</script>
</head>
<body>
<form>
<label for="item">Add an item: </label>
<input id="item" type="text" size="20"><br>
<input id="submitButton" type="button" value="Add!">
</form>
<ul id="itemList">
</ul>
<p>
Click an item to remove it from the list.
</p>
</body>
</html>


Reply With Quote

Bookmarks