Displaying output from different function in one innerHTML - javascript

I am trying to display two outputs in different functions into single innerHTML when the button clicked. However, I want it without using a global variable to store the output. I have tried using array for storing the string output, however, the error is whether the output is not displayed correctly or it will keep storing the string output when I used push() to store output inside the array
The HTML:
<div>
<button type="button" id="display">display</button>
<button type="button" id="stats">stats </button>
<p id="msg"></p>
</div>
The Script:
//declare global array
var array = [1,2,3];
function list(){
var output ="";
var i;
for (i =0; i < array.length; i++){
output = output + " " + array[i];
}
//this output will be displayed when the first button is clicked
output = "List of all values in the array: <br>" + output + "<br>";
document.getElementById("msg").innerHTML = output;
}
function stats(){
var output = "";
var sum = 0;
var i;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
output = output + "The number of values in the array: " + array.length + "<br>The total of all values in the array: " + sum;
//here I want to display the output of list() function + stats()
//when the second button is clicked
document.getElementById("msg").innerHTML = output;
}
function init() {
var btnList = document.getElementById("display");
var btnStats = document.getElementById("stats");
btnList.onclick = list;
btnStats.onclick = stats;
}

It's simple just call list() inside stats() and then append the innerHTML.
The updated Script
var array = [1,2,3];
function list(){
var output ="";
var i;
for (i =0; i < array.length; i++){
output = output + " " + array[i];
}
//this output will be displayed when the first button is clicked
output = "List of all values in the array: <br>" + output + "<br>";
debugger;
document.getElementById("msg").innerHTML = output;
}
function stats(){
var output = "";
var sum = 0;
var i;
for (i = 0; i < array.length; i++) {
sum += array[i];
}
output = output + "The number of values in the array: " + array.length + "<br>The total of all values in the array: " + sum;
//here I want to display the output of list() function + stats()
//when the second button is clicked
list();
document.getElementById("msg").innerHTML += output;
}
function init() {
var btnList = document.getElementById("display");
var btnStats = document.getElementById("stats");
btnList.onclick = list;
btnStats.onclick = stats;
}
init();

Related

Javascript how to define an object by array of objects

I recently started learning html/javascript and I want a temporary object to be filled with one of the objects from an array based on the current page number.
loadnextpage();
function loadnextpage() {
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' + curpage.title);
}
But when I try to run the code it keeps giving me an error message that curpage is undefined, after that it keeps running and thus the last line of code gives an error, when I ask for curpage.pageNumber. After that it stops running the code.
image clipping of my code with error message
What am I doing wrong?
edit:
here is the entire code:
var pagenumber = 0;
var receipt = [];
var price = 0;
var text = '{"page": [{"pageNumber": "1","title": "kies je formaat","optionName": "size","option": [{"text": "klein","value": "small","extraPrice": "100"},{"text": "middel","value": "medium","extraPrice": "200"},{"text": "groot","value": "large","extraPrice": "300"}]},{"pageNumber": "2","title": "kies je kleur","optionName": "colour","option": [{"text": "rood","value": "red","extraPrice": "10"},{"text": "groen","value": "green","extraPrice": "20"},{"text": "blauw","value": "blue","extraPrice": "30"}]}]}';
var allcontent = [];
allcontent = JSON.parse(text);
var imgpath = 'img/';
loadnextpage();
function loadnextpage(){
var curpage = allcontent[pagenumber];
pagenumber++;
changeDiv('title', '<span>' + curpage.pageNumber + '</span>' +
curpage.title);
var radiobuttons = '';
var radiobuttonid = [];
for(var i = 0; i < curpage.option.length; i++) {
var curradio = curpage.option[i];
radiobuttons += '<label><div class="selection-wrap">';
radiobuttons += curradio.text;
radiobuttons += ' <input type="radio" name="';
radiobuttons += curpage.optoinName;
radiobuttons += '" value="';
radiobuttons += curradio.value;
radiobuttons += '" id="';
radiobuttons += curpage.optoinName;
radiobuttons += '_';
radiobuttons += curradio.value;
radiobuttons += '"></div></label></br>';
radiobuttonid.push(curpage.optoinName + '_' + curradio.value)
}
changeDiv('choices', radiobuttons);
for(var i = 0; i < radiobuttonid.length; i++){
document.getElementById(radiobuttonid[i]).onclick = function(){
receipt[pagenumber-1] = curpage.option[i];
for(var i = 0; i < receipt.length; i++){
price += receipt[i].extraPrice;
}
changeImg('previewimg', imgpath + curpage.option[i].value +
'/preview.jpg');
changeDiv('previewprice', '<h1>€' + price + ',-</h1>');
};
}
};
function changeDiv(id, content) {
document.getElementById(id).innerHTML = content;
};
function changeImg(id, img){
document.getElementById(id).src = img;
};

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Replace , with <br>

Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length

javascript - unable to populate 2D array

My instructor tasked us to build a 2D array and populate it with values from our HTML form. He gave us this example to create the array.
var tasks = new Array();
var index = 0;
He then said to insert the values into the two columns using this code.
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
However, something about these two lines is causing the script to break, because when I comment them out the final line of my script returns a value to the correct div. When I uncomment these lines no value is returned. Is there something wrong in my syntax?
This is my complete js file:
var tasks = new Array();
var index = 0;
function addTask() {
var tempdate = new Date();
var temptask = document.getElementById("taskinfo").value;
var td = document.getElementById("taskdate").value;
tempdate = td + " 00:00";
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
index++
tasks.sort(function (a, b) { return b.date - a.date });
var tablecode = "<table class = 'tasktable'>" +
"<tr>"+
"<th>Date</th>"+
"<th>Task</th>"+
"</tr>";
for (var i = 0; i < tasks.length; i++) {
tablecode = tablecode + "<tr>" +
"<td>" + tasks[i]["Date"].toDateString() + " </td>" +
"<td>" + tasks[i]["Task"] + " </td>" +
"</tr>";
}
tablecode = tablecode + "</table>";
//I am only returning "temptask" to test with, I will be returning "tablecode".
document.getElementById("bottomright").innerHTML = temptask;
return false;
}
tasks[index] (in the first case, tasks[0]) doesn't yet exist, so you can't give it properties. Try this to create an object and assign it to tasks[index]:
tasks[index] = {
Date: tempdate,
Task: temptask
};
in place of
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;
Alternatively, you can use
tasks[index] = {};
tasks[index]["Date"] = tempdate;
tasks[index]["Task"] = temptask;

My javascript code is printing only one row. I need it to print 10 rows of 20 characters.

This is a coin flipping randomizer. I need to print out 10 rows and 20 columns. This is where I am stuck. My code seems to randomize correctly every time I click my button, it displays 20 columns but I cannot seem to get it to print a second row. It may be something simple that I am just not catching. Anything will be appreciated.
Javascript Code
function toss()
{
var heads = "x ";
var tails = "o ";
var rows = 0;
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++)
{
var val = Math.floor( Math.random() * 2 );
if(val === 1)
{
arr[i] = " x";
}
else
{
arr[i] = " y";
}
document.getElementById("results").innerHTML = arr + "<br />";
}
delete arr;
rows++
}
}
HTML:
<html>
<head>
<title>Coin Flip</title>
<script src="Toss.js" type="text/Javascript"></script>
<style>
#results
{
display: block;
}
</style>
</head>
<body>
Push Button to Flip -> <input type="button" onclick="toss()" value=" Flip ">
<span id="results"></span>
</body>
</html>
The problem is you are replacing the entire results output each time you create a row with the new row. You need to append instead of replace. So change this:
document.getElementById("results").innerHTML = arr + "<br />";
To:
document.getElementById("results").innerHTML += arr + "<br />";
You also need to move the append of the result out of the inner for loop! If you leave the append within the for loop, you will see this behavior: http://jsfiddle.net/t1s93Lqz/3/
JSFiddle: http://jsfiddle.net/t1s93Lqz/2/
You are resetting the html inside the element each iteration through the loop
document.getElementById("results").innerHTML = arr + "<br />";
And while you could concatenate innerHTML each iteration to fix this:
document.getElementById("results").innerHTML += arr + "<br />";
This will cause the whole html for that element to be re-rendered. It would be better to either build the html string first and then set the element's innerHTML property or use DOM methods like appendChild/insertAdjacentHTML.
Build string first
var html = "";
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
//moved the concatenation out of the loop
//otherwise you will get a line each as the array is set
html += arr + "<br />";
rows++
}
document.getElementById("results").innerHTML = html;
Using insertAdjacentHTML
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
Demo
var rows = 0;
var element = document.getElementById("results");
while(rows < 10)
{
var arr = new Array(20);
for(var i = 0; i < arr.length; i++) {
var val = Math.floor( Math.random() * 2 );
if(val === 1) {
arr[i] = " x";
} else {
arr[i] = " y";
}
}
element.insertAdjacentHTML('beforeend',arr+"<br />");
rows++
}
<div id="results"></div>
Also note your delete statement won't do anything as delete works on object properties, if you console.log( delete arr ) you will see it will print false
You are only printing the last row. Replace
document.getElementById("results").innerHTML = arr + "<br />";
with
document.getElementById("results").innerHTML += arr + "<br />";

Categories

Resources