Outputting array elements one at a time - javascript

Currently I am pushing form data (a single text field) to an empty array so that every time I click 'submit' the data is pushed to the end of the array (and thus, the array gets larger)
What I am experiencing:
I would like to output each element in a table, but I would like to do it one element per row, but right now it outputs like this per row
First row: Data entered and submit pressed once -> enteredData
Second row: More data entered and submit pressed -> enteredData
enteredData1
If I enter another element it does
enteredData
enteredData1
enteredData2
And so forth and so on....
Here's the code block that I have looping:
userInputName.push(userString);
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
}
I feel like I'm missing some kind of conditional logic inside the for loop, but at this moment (too little sleep) I can't piece it together rationally :|
Any suggestions on what I'm missing?
This is what my full javascript code block looks like--I may reference this to my other thread asking a related question:
//Declare global variable
var userInputName = [];
function displayTableAndTotals() {
// Your code goes in here.
//var totalStrings = [];
var userString;
var arrayIndex;
var output;
var outputTotal;
var form;
form = document.getElementById("userFormId");
output = document.getElementById("userEntriesId");
outputTotal = document.getElementById("testId");
userString = form.string.value;
userInputName.push(userString);
for (arrayIndex = 0; arrayIndex < userInputName.length; arrayIndex++) {
output.innerHTML += "<tr><td>" + userInputName[arrayIndex] + "</td></tr>";
}
form.string.select();
return false;
}

you could just add the pushed element
var table = document.querySelector('#myTable');
document.querySelector('[type="submit"]').addEventListener('click', function(e) {
table.innerHTML += "<tr><td>" + userInputName.reverse()[0] + "</td></tr>";
}, false);

Good grief, of course I solve my own problem AFTER I spent forever agonizing and then consulting.
Basically I needed to do this:
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;
So that the tableData variable would contain a new iteration without constantly resubmitting the entire thing every time. That way I could output tableData outside the loop properly.
I appreciate the feedback I have received.
Thank you!

Related

Issues attempting to display data from JSON file

Premise:
I'm playing around with javascript and have been trying to display a populated JSON file with an array of people on the browser. I've managed to display it through ajax, but now I'm trying to perform the same task with jQuery.
Problem:
The problem is that it keeps saying customerdata[i] is undefined and can't seem to figure out why.
$(function() {
console.log('Ready');
let tbody = $("#customertable tbody");
var customerdata = [];
$.getJSON("MOCK_DATA.json", function(data) {
customerdata.push(data);
});
for (var i = 0; i < 200; i++) {
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " + customerdata[i].city + '<br>' + "Email: " + customerdata[i].email + '<br>' + '<a href=' + customerdata[i].website + '>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
SAMPLE CONTENT OF MOCK_DATA.json
[
{"id":1,"first_name":"Tracey","last_name":"Jansson","email":"tjansson0#discuz.net","gender":"Female","ip_address":"167.88.183.95","birthdate":"1999-08-25T17:24:23Z","website":"http://hello.com","city":"Medellín","credits":7471},
{"id":2,"first_name":"Elsa","last_name":"Tubbs","email":"etubbs1#uol.com.br","gender":"Female","ip_address":"61.26.221.132","birthdate":"1999-06-28T17:22:47Z","website":"http://hi.com","city":"At Taḩālif","credits":6514}
]
Firstly, you're pushing an array into an array, meaning you're a level deeper than you want to be when iterating over the data.
Secondly, $.getJSON is an asynchronous task. It's not complete, meaning customerdata isn't populated by the time your jQuery is trying to append the data.
You should wait for getJSON to resolve before you append, by chaining a then to your AJAX call.
$.getJSON("MOCK_DATA.json")
.then(function(customerdata){
for(var i = 0; i < 200; i++){
//Cell for name
let nameTD = $('<td>').text(customerdata[i].first_name + ", " + customerdata[i].last_name);
//Cell for birthdate
let mDate = moment(customerdata[i].birthdate);
let formattedmDate = mDate.format('YYYY-MM-DD');
let birthdateTD = $('<td>').text(formattedmDate);
//Cell for Address
let addressTD = $('<td>').html("City: " +
customerdata[i].city + '<br>' + "Email: " +
customerdata[i].email + '<br>' + '<a
href='+customerdata[i].website+'>Website</a>');
//Cell for Credits
let creditTD = $('<td>').text(customerdata[i].credits);
let row = $('<tr>').append(nameTD).append(birthdateTD).append(addressTD).append(creditTD);
tbody.append(row);
}
})
You also won't need to define customerdata as an empty array at all with this approach.
The problem is that data is already an array.
so you should use:
customerdata = data;
otherwhise you are creating an array in the pos 0 with all the data

Output in div, prints objects in array, but first answer is "Undefined". - Javascript

I'm very new to this, and I was hoping to get some clarity in this:
Whenever I run this code (PS: boardGames, is an array in a separate doc) It seems to work, but the first answer is always "undefined". Why is that? and how can I fix it?
Thanks!
var message;
var games;
var search;
var i;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function gamestoPlay( games ) {
var topGames = '<h3> Game: ' + boardGames[i].name +'</h3>';
topGames += '<p> Minimum Players: ' + boardGames[i].idealMinPlayers + '</p>';
topGames += '<p> Maximum Players: ' + boardGames[i].idealMaxPlayers + '</p>';
return topGames
}
search = parseInt(prompt('How many people are coming?'));
for (i = 0; i < boardGames.length; i += 1) {
games = i;
if ( search >= boardGames[i].idealMinPlayers && search <= boardGames[i].idealMaxPlayers) {
message += gamestoPlay();
print(message);
}
}
Because you didn't initialize message.
When you do
message += gamesToPlay();
it first has to convert message to a string so it can concatenate to it. Since you didn't initialize message, its value is undefined, and when this is converted to a string it becomes "undefined", and then the result of gamesToPlay() is concatenated to that.
Change the initialization to:
var message = "";

can't get the results of select query in an array with javascript

I have a problem when trying to store the results of a select query into an array with java script .
the problem is that inside the function the array is containing the right values but outside it's empty , even when i used a global var it's still empty !!!
db.transaction(function (transaction) {
var sql = "SELECT * FROM Question where idEnq=" + idEn;
transaction.executeSql(sql, undefined, function (transaction, result) {
var res = document.getElementById('results');
res.innerHTML = "<ul>";
if (result.rows.length) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
ch[i] = new qu(row.id, row.text, row.type);
res.innerHTML += '<li>' + row.id + ' ' + ch[i].text + ' ' + ch[i].type + '</li>';
}
tablo = ch;
} else {
alert("No choices");
res.innerHTML += "<li> No choices </li>";
}
res.innerHTML += "</ul>";
}, onError);
}); // here the ch and the tablo array are empty
You are using asynchronous functions. Anything that wants to use the data "returned" by those functions need to be in the callback. Of course you can assign this data e.g. to a global variable, but that variable will only have the value after the callback has run (asynchronously).
you're new so have look here http://pietschsoft.com/post/2008/02/JavaScript-Function-Tips-and-Tricks.aspx
there's a part talking about calling JavaScript Function asynchronously

post data from table row like json format

this is related to my last question(
NOTE: I already got some good answers there). I'm doing a program that will filter. I didn't include this question because i thought that it is easier for me to add text as long as i know how to get the data from the row. But to my dismay, I wasn't able to code a good program til now.
Im currently using this javascript code (thanks to Awea):
$('#out').click(function(){
$('table tr').each(function(){
var td = '';
$(this).find('option:selected').each(function(){
td = td + ' ' + $(this).text();
});
td = td + ' ' + $(this).find('input').val();
alert(td);
});
})
my question is: How to add text before the data from the row? like for example, this code alert
the first row like data1.1 data1.2 data1.3,
then the second row like data2.1 data2.2 data2.3,
I want my output to be displayed like this
[
{"name":"data1.1","comparison":"data1.2", "value":"data1.3"},
{"name":"data2.1","comparison":"data2.2", "value":"data2.3"},
{"name":"data3.1","comparison":"data3.2", "value":"data3.3"}
{.....and so on......}]
but before that happen, i want to check if all the FIRST cell in a row is not empty. if its empty, skip that row then proceed to next row.
is there somebody can help me, please...
Building on my answer to your previous question, see http://jsfiddle.net/evbUa/1/
Once you have your data in a javascript object (dataArray in my example), you can write the JSON yourself, per my example, but you will find it much easier to use a library such as JSON-js (see this also).
// object to hold your data
function dataRow(value1,value2,value3) {
this.name = value1;
this.comparison = value2;
this.value = value3;
}
$('#out').click(function(){
// create array to hold your data
var dataArray = new Array();
// iterate through rows of table
for(var i = 1; i <= $("table tr").length; i++){
// check if first field is used
if($("table tr:nth-child(" + i + ") select[class='field']").val().length > 0) {
// create object and push to array
dataArray.push(
new dataRow(
$("table tr:nth-child(" + i + ") select[class='field']").val(),
$("table tr:nth-child(" + i + ") select[class='comp']").val(),
$("table tr:nth-child(" + i + ") input").val())
);
}
}
// consider using a JSON library to do this for you
for(var i = 0; i < dataArray.length; i++){
var output = "";
output = output + '{"name":"data' + (i + 1) + '.' + dataArray[i].name + '",';
output = output + '"comparison":"data' + (i + 1) + '.' + dataArray[i].comparison + '",';
output = output + '"value":"data' + (i + 1) + '.' + dataArray[i].value + '"}';
alert(output);
}
})
There are two things you need to do here. First get the data into an array of objects, and secondly get the string representation.
I have not tested this, but it should give you a basic idea of what to do.
Edit Please take a look at this JS-Fiddle example I've made. http://jsfiddle.net/4Nr9m/52/
$(document).ready(function() {
var objects = new Array();
$('table tr').each(function(key, value) {
if($(this).find('td:first').not(':empty')) {
//loop over the cells
obj = {};
$(this).find('td').each(function(key, value) {
var label = $(this).parents('table').find('th')[key].innerHTML;
obj[label] = value.innerHTML;
});
objects.push(obj);
}
});
//get JSON.
var json = objects.toSource();
$('#result').append(json);
});
var a = [];
a[0] = "data1.1 data1.2 data1.3"
a[1] = "data1.6 data1.2 data1.3"
var jsonobj = {};
var c = []
for (var i = 0;i
alert(c); //it will give ["{"name":"data1.1","comp...1.2","value":"data1.3"}", "{"name":"data1.6","comp...1.2","value":"data1.3"}"]
u have to include library for function from JSON.stringify from
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
hope this helps

How can I start with <a href=" and have an array element here then end with </a>?

The thing im trying to do right now is pulling in multiple links from a textarea,
We can pretend that a user inputs c:\pics\img01.jpg and in the next row he'll have the next imglink.
I want to pull those links, I allready have the code for that:
var entered = $('#filedir').val();
var lines = entered.split(/\r\n/);
var opttext = "";
for(var i=0;i<lines.length;i++) {
opttext += '< img src="' + lines[i] + '">< /img>';
}
​
the problem is in the output which is:
< img src="file:///C:/pics/img01.jpgc:/pics/img02.jpg">< /img>
There should be two < img> elements..
Where am I going wrong?
I've been at it for a bit over 2 hours now..
It's likely that your lines aren't getting split correctly and you're ending up with one long line in the array. Try this instead:
var lines = entered.split(/\n/);
for(var i=0;i<lines.length;i++)
{
opttext += '<img src="' + lines[i] + '"></img>';
}
Your for loop was incorrect.

Categories

Resources