Printing an object within an array showing as blank - javascript

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
if(objEvent.name.length > 0) {
arrEvent.push(objEvent);
}
}
displayEvent(arrEvent);
}
window.onload = init;
Trying to print an object array into the HTML paragraph id and whenever I execute the code above I get the correct output but the array elements just show as blank.

You are always pushing the same object into your array.
Change to:
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
ind += 1;
vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(name.length > 0) {
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
if(name.length > 0) {
arrEvent.push({name: name, age: age});
}
}
displayEvent(arrEvent);
}
window.onload = init;

Related

Issue with evaluating average of an array

I am trying to display an array of test scores and above them, the average of those scores. Here is the code I am using:
var clickDisplayResults = function () {
$("results").value = "";
function calculate(scores) {
var i = 0, sum = 0, len = scores.length;
while (i < len) {
sum = sum + scores[i++];
};
return sum / len;
};
var average = calculate(scores);
$("results").value = "The average score is: " + parseInt(average) + "\n";
$("results").value += "High Score: " + Math.max.apply(null, scores) + "\n";
$("results").value += "Low Score: " + Math.min.apply(null, scores) + "\n" + "\n";
for (var i = 0; i < names.length; i++) {
$("results").value += names[i] + ", " + scores[i] + "\n";
};
When I do this, however, I get an average in a ridiculous range after adding a new score.
Here is the add score code:
var clickAddScore = function () {
if ( $("name").value == "" || $("score").value < 0 || $("score").value > 100 || isNaN($("score").value) ) {
alert("Please enter a valid name and score");
$("name").value = "";
$("score").value = "";
return false;
};
else {
names[names.length] = $("name").value;
scores[scores.length] = $("score").value;
$("name").value = "";
$("score").value = "";
};
};
Any advice would be appreciated.
You are working with a string and treating it like a number
console.log("100" + 100);
You need to convert the string to a number. You can use parseInt, parseFloat, Number, or Unary plus.
Your code is a bit inefficient since you keep accessing the DOM for the value so declare some variables. And your else statement was wrong.
var clickAddScore = function() {
var studentName = $("name").value.trim();
var score = Number($("score").value);
if (studentName == "" || score < 0 || score > 100 || isNaN(score)) {
alert("Please enter a valid name and score");
} else {
names.push(studentName);
scores.push(score);
}
$("name").value = "";
$("score").value = "";
}

getting the variable's value from another funtion

Is there a way to get the 'username' and 'questionid' variable's value in my send() function like how I did with inputText?
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
var username = data[0].username;
//var examid = data[1].examid;
var questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);
You do not need var before username and questionid in your renderHTML function, as they have already been defined:
var username;
var questionid;
function renderHTML(data) {
var htmlString = "";
username = data[0].username;
//var examid = data[1].examid;
questionid = data[2].questionid;
for (var i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].questionid + "." + "\n" + "Question: " + data[i].question + "\n" + "<input type='text'>";
htmlString += '</p>';
}
response.insertAdjacentHTML('beforeend', htmlString);
}
function send() {
var inputText = document.querySelectorAll("input[type='text']");
var data = [];
for (var index = 0; index < inputText.length; index++) {
input = inputText[index].value;
data.push({
'text': input
});
}
console.log(data);

Removing random element from an array /Javascript

I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.
You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.
Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);
You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}
#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));
Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}

Unexpected end of input JavaScript

Can somebody please tell me what is wrong with the JavaScript in this code? It said "Unexpected end of input", but I do not see any errors. All my statements seem to be ended at some point, and every syntax checker says that no errors were detected.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<title>Slide Editor</title>
<style>
#font-face {
font-family: SegoeUILight;
src: url(Segoe_UI_Light.ttf);
}
* {
font-family: SegoeUILight;
}
</style>
<script src="Slide/RevealJS/lib/js/html5shiv.js"></script>
<script src="Slide/RevealJS/lib/js/head.min.js"></script>
</head>
<body onload="editSlideshow()">
<div id="sl">
<span id="sls"></span>
</div>
<span id="slt"></span>
<div id="editor">
</div>
<script>
function getURLParameters(paramName) {
var sURL = window.document.URL.toString();
if (sURL.indexOf("?") > 0) {
var arrParams = sURL.split("?");
var arrURLParams = arrParams[1].split("&");
var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);
var i = 0;
for (i = 0; i < arrURLParams.length; i++) {
var sParam = arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}
for (i = 0; i < arrURLParams.length; i++) {
if (arrParamNames[i] == paramName) {
//alert("Parameter:" + arrParamValues[i]);
return arrParamValues[i];
}
}
return "No Parameters Found";
}
}
var name = getURLParameters("show");
var slideCount = 1;
function editSlideshow() {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
slideCount = 1;
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
slideCount = textArray.length;
var slideCnt = textArray.length - 1;
for (var i = 0; i <= slideCnt; i++) {
$("#sls").append('<button onclick = "loadSlide\'' + (i + 1) + '\')" id = "slide_' + (i + 1) + '">Slide ' + (i + 1) + '</button>');
};
$("sl").append('<button onclick = "newSlide()">New Slide</button>');
};
};
function loadSlide(num) {
var array = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (array == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else if (array[num - 1] == null) {
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
} else {
var slideArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = slideArray[num - 1];
document.getElementById("editor").innerHTML = "<p><textarea rows = '15' cols = '100' id = 'editTxt'></textarea></p>";
document.getElementById("editTxt").value = text;
document.getElementById("slt").innerHTML = "Slide " + num;
$("#editor").append("<p><button onclick = 'saveSlide(\"" + num + "\")'>Save Slide</button><button onclick = 'deleteSlide(\"" + num + "\")'>Delete Slide</button></p>");
};
};
function saveSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
var text = document.getElementById("editTxt").value;
var textArray = new Array();
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
var text = document.getElementById("editTxt").value;
textArray[num - 1] = text;
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
};
};
function newSlide() {
var nextSlide = slideCount + 1;
$("#sls").append('<button onclick = "loadSlide(\'' + nextSlide + '\')" id = "slide_' + nextSlide.toString() + '">Slide ' + nextSlide.toString() + '</button>');
slideCount = nextSlide;
};
function deleteSlide(num) {
if (localStorage.getItem("app_slide_doc_" + name) == null) {
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
} else {
var textArray = JSON.parse(localStorage.getItem("app_slide_doc_" + name));
if (num !== "1") {
$("#slide_" + num).remove();
document.getElementById("editor").innerHTML = "";
document.getElementById("slt").innerHTML = "";
slideCount = slideCount - 1;
textArray.splice((num - 1), 1);
localStorage.setItem("app_slide_doc_" + name, JSON.stringify(textArray));
location.reload();
} else {
alert("The first slide cannot be deleted.");
};
};
};
</script>
</body>
</html>
You've gotten the punctuation wrong in more than one of your onclick attributes, for instance here:
$("#sls").append('<button onclick = "loadSlide\'1\')" id = "slide_1">Slide 1</button>');
It's missing the opening parenthesis. The reason syntax checks don't immediately catch this is because you're putting code inside a string. Which you should not do.
Since you're using jQuery, how about using .click(function() { ... }) instead of inline attributes? Just be careful to get your captured variables correct.
The problem at line 63
$("#sl").append('button onclick = "newSlide()">New Slide</button>');
Should be:
$("#sl").append('<button onclick = "newSlide()">New Slide</button>');

While loop + switch

I can't figure this out I keep getting stuck in a loop. I don't know if I have my calculation or if statements in the right areas, please I could use some help. My output is like a end of day report. I could really use the help.
<script type="text/javascript">
<!--
// assignments
var cost, nachosCounter, moneyCollected, nachosRate, corndogRate, hotdogRate;
var hamAccum, hotdogAccum, corndogAccum, nachosAccum, hamburgerRate;
var beginDay, orderType, hamCounter, hotdogCounter, corndogCounter;
var totalHotdog, totalNachos, totalCorndog, totalHamburger, moneyCollected;
var hamburgerRate = 4;
var hotDogRate = 2;
var cornDogRate = 3;
var nachosRate = 5;
var hamCounter = 0;
var hotdogCounter = 0;
var corndogCounter = 0;
var nachosCounter = 0;
var beginDay = "yes"
//initalizing loop
beginDay = "yes"
//start loop
while (beginDay == "yes")
{
orderType = prompt("hamburger, hotdog, corndog, nachos", "");
if (orderType == "hamburger")
{
hamCounter = hamCounter + 1;
if (hamCounter == 1)
{
hamAccum = "<br>The total number of hamburgers purchased: " + hamCounter;
}
else
{
hamAccum = hamAccum + "<br>" + hamCounter;
}
}
else if (orderType == "hotdog")
{
hotdogCounter = hotdogCounter + 1;
if (hotdogCounter == 1)
{
hotdogAccum = "The total number of hotdog purchased:<br>" + hotdogCounter;
}
else
{
hotdogAccum = hotdogAccum + "<br>" + hotdogCounter;
}
}
if (orderType == "corndog")
{
corndogCounter = corndogCounter + 1;
if (corndogCounter == 1)
{
corndogAccum = "<br>The total number of corndogs purchased: <br>" + corndogCounter;
}
else
{
corndogAccum = corndogAccum + "<br>" + corndogCounter;
}
}
if (orderType == "nachos")
{
nachosCounter = nachosCounter + 1;
if (nachosCounter == 1)
{
nachosAccum = "<br>The total number of nachos purchased: <br>" + nachosCounter;
}
else
{
nachosAccum = nachosAccum + "<br>" + nachosCounter;
}
}
totalHotdog = hotdogCounter*hotDogRate;
totalHamburger = hamCounter*hamburgerRate;
totalCorndog = corndogCounter*cornDogRate;
totalNachos = nachosCounter*nachosRate;
moneyCollected = totalNachos+totalCorndog+totalHamburger+totalHotdog;
beginDay = prompt("More to add?", "yes");
}
//output
document.write(hotdogAccum);
document.write(hamAccum);
document.write(corndogAccum);
document.write(nachosAccum);
document.write("<br>The total dollar amount for hotdog: $ " + totalHotdog);
document.write("<br>The total dollar amount for hamburger: $ " + totalHamburger);
document.write("<br>The total dollar amount for corndogs: $" + totalCorndog);
document.write("<br>The total dollar amount for nachos: $" + totalNachos);
document.write("The total amount of money collected: $" + moneyCollected);
// -->
</script>

Categories