turning a for loop into while loop - javascript

what is the best way to convert this into a while loop?
<html>
<head>
<script type="text/javascript">
<!--
function GetGrades() {
var grades = [];
var grade;
var sum = 0;
for(i=0; i<5; i++) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
}
for(i=0; i<5; i++) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
}
var avg = sum/5.0;
document.write("</br>Grade: " + avg + "</br>");
}
//-->
</script>
</head>
<body onload="GetGrades()">
</body>
</html>
I have ignorantly tried to simply declare the variable i as sero and change the for to while.

while(i<5) {
grade = prompt("Enter Homework " + (i+1) + " grade: ");
grades.push(Number(grade));
i++;
}
while(i<5) {
document.write("Homework " + (i+1) + " grade: " + grades[i] + "</br>");
sum = sum + grades[i];
i++;
}

Related

Toggle function problem, What am I doing wrong?

I've created a comment system that posts comments in an ordered list. My requirememnts were to add hide/show toggle function to each comment.
Currently, the toggle function only works on the first comment (even when you try to click on 2nd, 3rd, etc.)
I've tried to use querySelectAll, but it didn't work for me. What am I doing wrong?
<div class="textbox">
<h3>Leave comments</h3>
<label for=msg>Name</label><br>
<input type=text id=fname> <br>
<label for=msg>Content</label><br>
<textarea id=msg> </textarea>
<br>
<input type=button onclick="postcomments()" value="Send" />
<input type="reset" value="Reset" />
<ol id="showcomments" style="max-width:200px; font-size:12px; padding-left:10px;">
</ol>
</div>
<script>
var ans = [];
function postcomments() {
var fname = document.getElementById("fname").value;
var msg = document.getElementById("msg").value;
var lastpos = ans.length;
var current = new Date();
console.log(current);
var time = current.getHours() + ":" + (current.getMinutes() < 10 ? '0' : '') + current.getMinutes();
var date = current.getDate() + "." + (current.getMonth() + 1) + "." + current.getFullYear();
var i = 0;
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(document.getElementById("txt&quot))" style="width:8%;" id="plusminusicon">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
var ol = document.getElementById("showcomments");
ol.innerHTML = "";
for (var i = 0; i < ans.length; i++) {
ol.innerHTML += "<li id=" + (i + 1) + ">" + ans[i] + "</li>";
}
}
function toggle(x) {
if (x.style.display === "none") {
x.style.display = "block";
document.getElementById("plusminusicon").src = "Media/minusicon.png";
} else {
x.style.display = "none";
document.getElementById("plusminusicon").src = "Media/plusicon.png";
}
}
</script>
You have always the same id for all "txt" span, so the browser change always the first.
If you don't want change much of your code the simpliest solution is add the lastpost variable to the span id and to the parameter of toggle function.
Here the changes to do:
ans[lastpos] = '<img src="Media/minusicon.png" alt="minusicon" onclick="toggle(' + lastpos + ')" style="width:8%;" id="plusminusicon' + lastpos + '">' + " " + "Sent By" + " " + '' + fname + '' + " " + " In" + " " + date + " " + "At" + " " + time + '<br>' + '<span id="txt' + lastpos + '" class="toggle_panel">' + msg + '</span>' + '<br>' + '-------------------------------';
function toggle(x) {
let comment = document.getElementById("txt" + x);
let icon = document.getElementById("plusminusicon" + x);
if (comment.style.display === "none") {
comment.style.display = "block";
icon.src = "Media/minusicon.png";
} else {
comment.style.display = "none";
icon.src = "Media/plusicon.png";
}
}
To bind click listeners to dynamically added elements, you can use event delegation.
document.addEventListener('click', function(e) {
if (e.target && e.target.classList.contains('comment')) {
// do something
}
})
jQuery makes it even easier.
$(document).on('click','.comment',function(){ //do something })
And here's a jsfiddle link to the complete code example. https://jsfiddle.net/ep2bnu0g/

Calculating average from array and recieving a NaN error

I'm having issues with trying to convert objects from a string array into integers. I've used parseInt and parseFloat but none of it is working. Do I need to maybe structure the array declaration differently or the prompt?
Thanks guys
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=1; i<=10; i++){
scores[i] = prompt("Enter score " + i);
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(sum + scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
You're using the for loop for prompt from 1 to 10, but calculating the sum in Average looping 0 to 9. The scores[0] is undefined as it is never assigned a value in the prompt loop whcih results to NaN when added to other numbers. Also you're adding sum in parseInt which is wrong.
Here is the fixed code :
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Hope this helps !
following line is wrong in your code :
scores[i] = prompt("Enter score " + i);
I have written a small piece of javascript code which will do the average calculation. What it's doing is, getting the number in a variable from the prompt and pushing it into the array.
function calAverage(){
var sum = 0;
for (var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
return avg;
}
var scores = [];
for (var i=1; i<=10; i++){
var number = prompt("Enter score :");
scores.push(parseInt(number));
}
console.log(scores);
var average = calAverage(scores);
console.log("Average = " + average);
There are a few issues here:
scores[i] = prompt("Enter score " + i);, I would exchange this for scores.push(parseInt(prompt("Enter score " + i)));, as prompt returns a string, upon which most operations will fail and return NaN. Setting scores[i] = does work, but can be messy if you try to scale it up.
sum += parseInt(sum + scores[i]);, you have already got the +=, and as such the extra sum + ... effectively translates to sum = (2 * sum) + scores[i], meaning we can reduce this to sum += scores[i];
The complete code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores.push(parseInt(prompt("Enter score " + i)));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += scores[i];
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Here's the working code:
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<=9; i++){
scores[i] = prompt("Enter score " + (i+1));
document.writeln("<tr><td style='padding: 5px;'><b>Score " + (i + 1) + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i], 10);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
Thanks for the help, Andreas.
I did some modification in your code and also applied a check if user enter any value other than a number.
var scores = [];
document.writeln("<font face='arial' size=''><table border='1' style='border-collapse: collapse;'>")
for(var i=0; i<10; i++){
scores[i] = parseFloat(prompt("Enter score " + (i+1)));
if(isNaN(scores[i])){
scores[i]=0;
}
document.writeln("<tr><td style='padding: 5px;'><b>Score " + i + "</b></td>");
document.writeln("<td style='padding: 5px;' contenteditable='true'><center>" + scores[i] + "</center></td>");
document.writeln("</tr>");
}
Average();
function Average(){
var sum = 0;
for(var i = 0; i < scores.length; i++){
sum += parseInt(scores[i]);
}
var avg = sum/scores.length;
document.getElementById("average").innerHTML = ("Your score average is: " + avg);
}
<div id="average"></div>

how can the if (){}else{} statement execute both outcomes

I want to create a basic search engine that searches students already existing in an array of objects by first name and last name and if it finds a student named that way enlist it on the page, and if it doesn't write on the page it doesn't exist. but when I have 2 people with the same first name, it gives me both outcome of the if statement. can someone help, please
searchButton.addEventListener("click", function () {
userSearch = searchInput.value;
for (i = 0; i < allStudents.length; i++) {
student = allStudents[i];
if(userSearch.toLowerCase() === student.firstName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.firstName.toLowerCase() + " " + student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() + " " + student.firstName.toLowerCase()) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
searchInput.value = "";
} else {
searchInput.value = "";
outputDiv.innerHTML += "<h2>The student you searched for is not in out database</h2>"
}
}
});
You might want to change your logic as you have two tasks:
Find if the student exists
Display students if available else show message
You can use a variable (found) to keep track of whether any students were found in allStudents, that way you won't have to worry about the else condition executing more than once
let allStudents = [{
firstName: "George",
lastName: "A"
}, {
firstName: "George",
lastName: "B"
}]
searchButton.addEventListener("click", function() {
outputDiv.innerHTML = "";
userSearch = searchInput.value;
var found = false;
for (i = 0; i < allStudents.length; i++) {
student = allStudents[i];
if (userSearch.toLowerCase() === student.firstName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.firstName.toLowerCase() + " " + student.lastName.toLowerCase() ||
userSearch.toLowerCase() === student.lastName.toLowerCase() + " " + student.firstName.toLowerCase()) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
found = true;
}
}
if (!found)
outputDiv.innerHTML = "<h2>The student you searched for is not in out database</h2>";
searchInput.value = "";
});
<input id="searchInput" value="George" />
<button id="searchButton">search</button>
<div id="outputDiv"></div>
You need to rearrange the check to see if it's found or not. You are outputting "that student was not found in our database" INSIDE the loop of students, so it's outputting that text even if another result (in the loop) WAS found. I have corrected that issue by moving the check (for if a student was found) outside of the loop and using a variable to track that. I also changed some things so that you aren't reformatting names toLowerCase() in every loop or having to locate a DOM element.
searchInput = document.getElementById("search_text"),
searchButton = document.getElementById("SearchButton"),
outputDiv = document.getElementById("outputdiv");
searchButton.addEventListener("click", function () {
var userFound = false;
userSearch = searchInput.value;
studentLen = allStudents.length;
outputDiv.innerHTML = "";
for (i = 0; i < studentLen; i++) {
student = allStudents[i];
userSearch = userSearch.toLowerCase();
var fn = student.firstName.toLowerCase(),
ln = student.lastName.toLowerCase();
if(userSearch === fn || userSearch === ln || userSearch === fn + " " + ln || userSearch === ln + " " + fn) {
outputDiv.innerHTML += "<h2> Student: " + student.firstName + " " + student.lastName + "</h2><br>" +
"Age: " + student.age + "<br>" +
"Eye Color: " + student.eyeColor + "<br>" +
"Hair Color: " + student.hairColor + "<br>" +
"Programming Skills: " + student.programmingSkills
searchInput.value = "";
userFound = true;
}
}
if(!userFound){
outputDiv.innerHTML += "<h2>The student you searched for is not in out database</h2>";
}
});
Working fiddle with HTML/JS both included:
https://jsfiddle.net/Ltkacgn4/

Why is the output being overwritten for this javascript

Expanded a previous question and it is working fine with the exception to the daily output. As the user enters each week/daily intake of supplement packs it should display to screen until the number of days entered is met. If a user input 2 weeks and 3 days (number of days packs were taken each week) the output should look like:
Week 1
Number of packs taken on Day 1 = 2
Number of packs taken on Day 2 = 1
Number of packs taken on Day 3 = 3
Week 2
Number of packs taken on Day 1 = 1 etc....
My code keeps writing over Week 1. I'm sure this is something simple that I overlooked. Maybe a variable to hold each weeks input? My code thus far...thanks for the help.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Daily Supplement Intake Log</title>
<script>
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
while(i < numWeeks) {
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
while(d < daysPerWeek){
var packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
subtotal is " + sum + " supplement packs." + "<br>"
+ "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
}
document.getElementById("output4").innerHTML="The total for these weeks
is " + grandTotal + " supplement packs." + "<br>";
}
</script>
<body>
<header><h1>Daily Supplement Packet Log</h1></header><br>
<section>
<div class="align">
<label>Number of weeks:</label>
<input type="text" name="textbox" id="week" value=""><br>
<label>Number of days per week:</label>
<input type="text" name="textbox" id="day" value=""><br></div>
<div id="button">
<button type="button" id="log" onclick="getSup()">Enter number of packs
taken each day</button></div>
</section>
<div id="output1"></div>
<div id="output2"></div>
<div id="output3"></div>
<div id="output4"></div>
</body>
</html>
Using document.createElement method to dynamically create and order output divs. JSFiddle demo.
First replace your <div id="output1"></div>, ...2, ...3, and ...4 divs with:
<div id="outputs"></div>
<div id="total"></div>
...and then swap your getSup function with this:
function getSup() {
var numWeeks = parseInt(document.getElementById("week").value);
var daysPerWeek = parseInt(document.getElementById("day").value);
var sum = 0;
var i = 0;
var total = 0;
var d = 0;
var grandTotal = 0;
var maxPacks = 0;
var highDay = 0;
var packsTaken;
var tempDiv, weekListText
var outputs = document.getElementById("outputs");
while(i < numWeeks) {
d = 0;
grandTotal = 0;
maxPacks = 0;
highDay = 0;
weekListText = '';
while(d < daysPerWeek){
packsTaken = prompt("Enter the number of packs taken on week " + (i + 1) + " and day "+ (d + 1), "");
total = parseInt(packsTaken);
//document.getElementById("output2").innerHTML+="Number of packs for day " + (d + 1) + " = " + total + "<br />";
weekListText += "Number of packs for day " + (d + 1) + " = " + total + "<br />";
if(packsTaken > maxPacks){
maxPacks = packsTaken;
highDay = d;
}
sum += total;
d++;
}
grandTotal += sum;
i++;
//document.getElementById("output1").innerHTML="Week " + i + "<br />";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i;
outputs.appendChild(tempDiv);
// formerly known as output2
tempDiv = document.createElement('div');
tempDiv.innerHTML = weekListText;
outputs.appendChild(tempDiv);
//document.getElementById("output3").innerHTML="Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
tempDiv = document.createElement('div');
tempDiv.innerHTML = "Week " + i + "subtotal is " + sum + " supplement packs." + "<br>" + "Week " + i + " largest day is " + maxPacks + " packs, on day " + d + "<br>";
outputs.appendChild(tempDiv);
}
document.getElementById("total").innerHTML="The total for these weeks is " + grandTotal + " supplement packs." + "<br>";
}
This is mostly the same as the original, but I've rem'ed out the old innerHTML assignments and moved the vars up to the top of the function to reflect actual variable scope.
You overwrite the html, you do not append to it like you do in the loop.
document.getElementById("output1").innerHTML="Week " + i + "<br />";
document.getElementById("output3").innerHTML="Week " + i + "
should be
document.getElementById("output1").innerHTML += "Week " + i + "<br />";
document.getElementById("output3").innerHTML += "Week " + i + ";
but that is not going to make the output you want since they are the same sections. You really should be appending new elements to the page.
var header = document.createElement("h2");
header.innerHTML = "Week " + i;
document.getElementById("output1").appendChild(header);
var div = document.createElement("div");
div.innerHTML = "new content";
document.getElementById("output1").appendChild(div);

Prompt() method in Javascript

I'm a beginner to Javascript and I have a basic question about how to use the prompt method. None of the code seems to process below. Is there some sort of hidden rule about using multiple prompt boxes or does my code just have a syntax error? Any help would be much appreciated. Thanks in advance.
<html>
<head>
<title> Two Numbers </title>
<script type="text/javascript">
var first = prompt("Enter first number:");
var second = prompt("Enter second number:");
var sum = (first-0) + (second-0);
var diff = first - second;
var divide = first/second;
var multi = first*second;
document.write(first + " + " + second " = " + sum + "<br />");
document.write(first + " + " + second " = " + diff + "<br />");
document.write(first + " + " + second " = " + divide + "<br />");
document.write(first + " + " + second " = " + multi + "<br />");
</script>
</head>
<body>
</body>
</html>
You're missing a +.
//change this
console.log(first + " + " + second " = " + sum + "<br />");
// to this
console.log(first + " + " + second + " = " + sum + "<br />");
In the future, please use the console for debugging. There is a great article on everything you can do with the console here > https://developer.chrome.com/devtools/docs/javascript-debugging
Corrected the syntax error and corrected the operators in the write() function:
<html>
<head>
<title> Two Numbers </title>
<script type="text/javascript">
var first = prompt("Enter first number:");
var second = prompt("Enter second number:");
var sum = (first-0) + (second-0);
var diff = first - second;
var divide = first/second;
var multi = first*second;
document.write(first + " + " + second + " = " + sum + "<br />");
document.write(first + " - " + second + " = " + diff + "<br />");
document.write(first + " / " + second + " = " + divide + "<br />");
document.write(first + " * " + second + " = " + multi + "<br />");
</script>
</head>
<body>
</body>
</html>
use the console to check for errors, as said by James G
var isValid = true;
var first = prompt("Enter first number:");
if (!Number(first)) {
alert("Please enter numeric value only.");
isValid = false;
}
if (isValid) {
var second = prompt("Enter second number:");
if (!Number(second)) {
alert("Please enter numeric value only.");
isValid = false;
}
if (isValid) {
var sum = first + second;
var diff = first - second;
var divide = first / second;
var multi = first * second;
console.log(first + " + " + second + " = " + sum);
console.log(first + " - " + second + " = " + diff)
console.log(first + " / " + second + " = " + divide);
console.log(first + " * " + second + " = " + multi);
}
}

Categories