Log input into array, print only new input - javascript

Okay I have a a couple of functions. I don't think most of them are relevant. What I want to do is create an html list when you click a button, and store the value in an array. However I want to be able to update this list without outputting the entire array again. I have it set up to accept the input and I can get it to loop and print the array but it will print the entire array and I only want one. This seems like a common thing but my Google-fu returned nothing.
So I have a list variable that connects to an input, logs it into an array, and another function to clear it and print out the values.
Code snippet:
var listItemInput= document.getElementByID("listItem");
var listItem= [];
function insertListItem(){
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow(){
listItemInput.value= "";
}
function printList{
for (var i = 0; i < listItem.length; i++){
document.getElementById("list").innerHTML += '<li>' + listItem[i] + '</li>';
}
When the printList funciton is called by pressing the button it prints the entire array over however I would like a button that simply prints the newest item. How could I do that?
For clarification, I need to print out the list to html and store the values in an array, the values will later be referenced in an if else argument to combine and print them with new variables.
EDIT:
I plugged in the var = lastIndex and changed it as well as made two more variables for my list. This seems to make it work. Thank you.

You could keep track of the last index printed.
var listItemInput= document.getElementByID("listItem");
var listItem = [];
var lastIndex = 0; //Keep track of the last index shown.
function insertListItem() {
listItem.push(listItemInput.value);
clearAndShow();
}
function clearAndShow() {
listItemInput.value = "";
}
function printList() {
for (; lastIndex < listItem.length; lastIndex++) {
document.getElementById("list").innerHTML += '<li>' + listItem[lastIndex] + '</li>';
}
}
This approach assumes you won't be removing items from listItem array, which you didn't express is something that would be done.

If you only want one element, why do you need to iterate?
function printList() {
document.getElementById('list').innerHTML = '<li>' + listItem[listItem.length-1] + '</li>';
}

Related

Javascript For loop appending child only appends first element, then throws error

I'm looping through a js object with a nested for loop, stated below, it appends the first element correctly, but then throws the following error:
Can't set the property className of an undefined reference or empty reference. (not sure if exact error, translating from Dutch...)
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true}); //returns: [{"VideoName":"timelapse aethon2","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"},{"VideoName":"timelapse aethon3","VideoPath":"videos\\Roermond Papier\\160424 Time laps Aethon2.avi"}]
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
//alert(resultSet);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
videoElement.appendChild(document.createElement('div'));
videoElement.children[i].id='allVid' + i;
videoElement.children[i].className='col-md-4 col-xs-12';
//alert(typeof key)
var card = document.getElementById('allVid' + i);
alert(i);
card.appendChild(document.createElement('div'));
card.children[i].className='card card-block';
card.children[i].innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
}
}
}
}
[EDIT] added screenshot of how it looks
Your code has some significant logic issues. You're using nested loops, but appending to an element assuming that the outer loop counter will let you index into that element's children to get the element you just appended. Later, you try to get that same element again using getElementById. Then, you append a new element to your newly-created element, but try to access that new element using children[i] on the one you just created — at that point, the card element will only have a single child, so as of the second outer loop, it will fail.
createElement returns the element to you, so there's no reason at all to try to access it via children[i] (either time) or getElementById.
See comments:
function allVideos() {
var sql = "SELECT videos.VideoName, videos.VideoPath FROM videos";
var resultSet = db.query(sql, {json:true});
var parsed = JSON.parse(resultSet);
var parsedlength = arrLenght(parsed);
for(var i = 0; i < parsedlength; i++) {
var obj = parsed[i];
//alert(i);
var videoElement = document.getElementById("allVideos");
for (var key in obj) {
if(obj.hasOwnProperty(key)) {
// Create the card, give it its id and class
var card = document.createElement('div');
card.id='allVid' + i;
card.className='col-md-4 col-xs-12';
// Create the div to put in the card, give it its class and content
var div = document.createElement('div');
card.appendChild(div);
div.className='card card-block';
div.innerHTML = "<h3 class='card-title'>" + obj['VideoName'] + "</h3><button class='btn btn-primary'>Selecteren</button>"
// Append the card
videoElement.appendChild(card);
}
}
}
}
Side note: arrLenght looks like a typo (it should be th, not ht), but moreover, there's no reason to use a function to get the length of an array; it's available via the array's length property: parsedLength = parsed.length.
Side note 2: You may find these ways of looping through arrays useful.
Your problem is the if within the nested for:
if(obj.hasOwnProperty(key)) { ...
The variable i is increased even if the property is not "owned" (when the if condition returns false), so next time that the condition is true, i is out of bounds.

Get one div for every returned element

Im stuck.
I have a button which returns information about a event, name, date and so on.
In the script it looks like this:
for(var i = 0; i < result.length ; i++)
{
var item = result[i];
$("#eventList").append("<h3>" + result.eventDate + "</h3>" + "<br>" + result.eventId + "<br>" + result.description + "<br>");
}
This generates a list of events that goes to a div, alla of the events in one div. But i would like every event to be placed in one separate div/box.
Any ideas?
You can create them inside a div and then append all of them at the end to the dom.
var divs = [];
var $div;
results.forEach(function(item){
$div = $('<div></div>');
$div.append("<h3>" + item.eventDate + "</h3>");
$div.append("<br>"+ item.eventId);
$div.append("<br>"+ item.description);
divs.push($div);
});
$("#eventList").append(divs);
You can create your item variable inside the for loop. When ii gets too big, result[ii] will be undefined or false, and the loop will stop. I prefer to use ii to i, because it's easier to find if I want to search for a repeat loop.
Each jQuery operation returns the jQuery object that it was applied to, so you can chain your operations. You can create an empty element, and then set its text in the next operation, to make the code more compact.
for(var ii=0, item; item=result[ii]; ii++) {
$("#eventList")
.append($("<div>")
.append($("<h3>").text(item.eventDate))
.append($("<p>").text(item.eventId))
.append($("<p>").text(item.description))
)
}
jsFiddle

Displaying total array elements for array being built by form

I'm currently in a JavaScript course that is asking me to have the following happen:
User enters names one at a time into a form, then presses Submit
The names are stored into an array and output to a table
As names are entered (and added to the table), a total must update as well--based on the array, not just from counting table elements
My current issue is I'll add one name, then the total shows "1"--when I add a second name, the total displays "11"
This is currently what my JavaScript code looks like:
function displayNamesAndTotal() {
// Your code goes in here.
var userInputName = [];
var totalNamesEntered = [];
var countTotal = 0;
var firstName;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
//userInputName[0] = form.firstname.value;
userInputName.push(form.firstname.value)
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
countTotal += userInputName.length;
}
outputTotal.innerHTML += countTotal;
return false;
}
I've spent the past day or so trying to figure out what I'm doing wrong--and it's probably something embarrassingly easy--but I'm at a loss and could use guidance
Any suggestions?
Thanks
It looks like your total is storing a string instead of a number. Try using parseInt(number) to convert the string into a number.
Good grief, from reading the other answers from you guys I think I have it licked
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
tableData = "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
totalCount = userInputName.length;
}
output.innerHTML += tableData;
outputTotal.innerHTML = "<h4>Total Number of Strings: " + totalCount + "</h4>";
form.string.select();
return false;
This way the totalCount acted as the array's length when it went through the loop, then outside in the innerHTML statement I could display it and have it constantly update whenever a new string was submitted.
Thank you for all of your feedback
outputTotal.innerHTML is a string, so adding to it would concatenate the strings together. Since outputTotal.innerHTML starts out as null, add 1 to it creates "1". When you add 1 to it again, outputTotal.innterHTML is already "1", so it becomes "11".
Instead of incrementing outputTotal.innerHTML try setting the HTML to it directly.
outputTotal.innerHTML = countTotal;

How to stop innerHtml repeating itself over and over again in a table?

I have made an array with objects that get there info from three different user variables, however on one of these there are many sub variables that i don't want it to repeat itself every time the user presses the select button(which updates the table) instead i want it to just add onto (or take away) from the sections that it already has in the table. thanks(if you need the variable code let me know) I have been trying to solve thi for a while now! please help!!
//creating array
var gProducts = new Array();
var gTotalCost = 0;
// Adding Products to array gProducts
function addProduct
{
var product = new Object();
product.name = name;
product.cost = cost;
gProducts.push(product);
gTotalCost += parseInt(cost)
}
//Getting products from array, use of for in loop setting new table rows in blank var for each array item
function renderProducts()
{
var HTMLadd = ""
for (var i in gProducts)
{
if( gProducts[i].cost > 0){
HTMLadd = HTMLadd +
"<tr>"+
"<td class='tableSettings00' id=tableRow2 >" + gProducts[i].name +
"</td>"+
"<td class='tableSettings'>€<span id=tableRow2part2>" + gProducts[i].cost +
"</span></td>"+
"</tr>";
}
else
{
}
}
document.getElementById('tableRow').innerHTML = HTMLadd;
}
You're using a for in loop, when you probably wanted just a for loop.
Change this line to
for (var i in gProducts)
to
for (var i = 0; i < gProducts.length; i++)
With a for/in loop, the variable i will be an object, and not an integer.

Adding names to an array and outputting them to a table

I'm having some trouble getting my code to work. This is what I have so far.
function outputNamesAndTotal() {
var name;
var outputTable;
var inputForm;
var nameArray;
var outputDiv;
outputDiv = document.getElementById("outputDiv");
inputForm = document.getElementById("inputForm");
outputTable = document.getElementById("outputTable");
name = inputForm.name.value;
nameArray = [];
nameArray.push(name);
for (var i = 0; i > nameArray.length; i++) {
outputTable.innerHTML += "<tr>" + nameArray[i] + "</tr>";
}
inputForm.name.focus();
inputForm.name.select();
return false;
}
When I add the loop it breaks the code completely, but I can't figure out why.
What I'm trying to do is use an HTML form to get a name from the user. Once the user enters the name, the program adds the name to the array, and outputs each array entry to a row in a table.
It's pretty basic, but it's still giving me all kinds of trouble!
I think you are clearing your array of names every time you call the function. You should bring the line:
nameArray = [];
out and make it global.
I ran a quick test and the following code works in at least FireFox
Edited to use appendChild
<html>
<head>
<script type='text/javascript'>
var names = [];
function addName() {
var nameTxt = document.getElementById('name_txt');
var name = nameTxt.value;
names.push(name);
var outTable = document.getElementById('out_tbl');
var row = document.createElement('tr');
var entry = document.createElement('td');
var txt = document.createTextNode(name);
entry.appendChild(txt);
row.appendChild(entry);
outTable.appendChild(row);
var numDiv = document.getElementById('num_div');
removeAllChildren(numDiv);
var numTxt = document.createTextNode('You have ' + names.length + ' names');
numDiv.appendChild(numTxt);
}
function removeAllChildren(e) {
while (e.hasChildNodes()) {
e.removeChild(e.firstChild);
}
}
</script>
</head>
<body>
<table id='out_tbl'>
</table>
<div id='num_div'>You have 0 names</div>
<input id='name_txt' type='text'/>
<button onclick="addName()">CLICK</button>
</body>
</html>
Edit: Oh yeah and you are the fact that you are looping through the array every time. If you "globalize" the name array, you're gonna print the whole array every time you add a name.
Edit x2: the code you originally posted had nameArray as a local variable inside the function. This effectively clears the array every time you call the function. Then every time you call the function you add the current name to the now empty array, and loop through all 1 (one) elements that the array now holds.
What you want to do is "globalize" the name array, and remove the loop from your function. This will allow you to build up your name array across multiple calls, and works the way that you want it.
Also, innerHTML is not really the best way to add things to the page. I would suggest using appendChild().
-C
for (var i = 0; i > nameArray.length; i++) {
I think you mean i < nameArray.length

Categories

Resources