I’m trying to retrieve only word from inside each new instance of the newEntry object. It displays in the console every time I add a new word, but not when I assign it to .innerHTML. Can anyone help?
Full code:
<style type="text/css" media="screen">
#output { height: auto;}
</style>
<script type="text/javascript">
// Array to contain words
var wordList = Array();
// word list constructor
function addWord(word) {
this.word = word;
this.description = "a description of the word";
this.entryDate = "01.02.2012";
this.userName = "John Doe";
var newEntry = {
word: word,
description: description,
entryDate: entryDate,
userName: userName
};
wordList[wordList.length] = newEntry;
};
// collect data from form
function getFormData() {
var results = document.getElementById("textbox").value;
addWord(results);
var data = '<ul>';
var numObjects = "Number of words = " + wordList.length;
for (var x in wordList) {
var wordSet = wordList[x];
for (var item in wordSet.word[x]) {
console.log(wordSet.word);
data += "<li><a href='#'>" + wordSet.word + "</a></li>";
};
};
data += "</ul>";
document.getElementById("Objects").innerHTML = numObjects;
document.getElementById("Output").innerHTML = data;
// console.log(wordList);
};
</script>
</head>
<body>
<form id="form_id" name="form_name" action="" method="post">
<p><label for="text">Enter words:<br/></label>
<input type="textarea" id="textbox" />
<input type="button" value="Go" onclick="getFormData()"
</form>
<ul id="Output"></ul>
<div id="Objects"></div>
</body>
You’re overwriting the content of the ‘output’ div each time. You could try changing
to
Then you should see the proper output (sans styling, or line breaks, of course).
* Further update *
You’re using your arrays in some funky ways. You might want to just declare your array as a literal and then use the push method to append the entry to the array. For iterating over the array you should probably use the standard for loop [eg: for (var i = 0; i < arr. length; ++i) kind of syntax, or the array forEach syntax (if supported by your browser). for in will iterate over all the properties of the object, and while technically safe for an array, is somewhat of an advised-against practice.
Also, there’s really no reason to assign properties into ‘this’ if you are just going to wrap the elements in JSON and stuff them in the list.
I’d recommend something like the following:
Then when interacting with your word list you would say:
a la: