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 = "";
}
I cant solve this homework that needs to ask the user to enter student marks and output the minimum mark of the student, can someone please help me solve this problem:
<script>
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .').split(',');
return marks;
}
var studentMarks = getMarks();
var arrayLength = studentMarks.length;
var studentNumber = 0;
var msg = '';
var i;
for (i = 0; i < arrayLength; i++) {
studentNumber = (i + 1);
msg += 'student ' + studentNumber + ': ';
msg += studentMarks[i] + '%' + '<br />';
} document.getElementById('marks').innerHTML = msg; document.getElementById('marke').innerHTML = math.min.apply(null, studentMarks) + '%';
</script>
I will do that in the following way:
function getMarks() {
var marks = prompt('Type the students marks, seperate each student mark with comma, do not write the percentage mark % .');
return marks.split(',').map(n => Number(n));
}
var marksArray = getMarks();
var studentMarks = Math.min(...marksArray);
var position = marksArray.indexOf(studentMarks);
var msg = 'Student ' + Number(position + 1) + ': ';
document.getElementById('marks').innerHTML = msg + studentMarks + '%';
<p id="marks"></p>
I need to display a date from an array and it needs to be incremented for each input by 1 day. The date should display as mm/dd/yyyy. I was able to get the date to display correctly with the code that is in the message but after each input the all the dates would increment. I need just the last input to increment a day and I thought putting it in an array would work but now nothing displays. Thanks for helping.
var lowTempArray = [];
var highTempArray = [];
var nowArray = [];
function process() {
'use strict';
//declare variables
var lowTemp = document.getElementById('lowTemp');
var highTemp = document.getElementById('highTemp');
var output = document.getElementById('output');
var date = new Date();
var message = ' ';
if (lowTemp.value) {
lowTempArray.push(lowTemp.value);
if (highTemp.value) {
highTempArray.push(highTemp.value);
message = '<table><th>Date </th><th> Low Temperatures</th><th> High Temperatures</th>';
for (var i = 0, count = lowTempArray.length; i < count; i++) {
for (var i = 0, count = highTempArray.length; i < count; i++) {
for (var i = 0, count = nowArray.length; i < count; i++) {
nowArray.push(new Date(date.getTime()));
date.setDate(date.getDate() + count);
message += '<tr><td>' + ((nowArray.getMonth() + 1) + '/' + (nowArray.getDate() + count) + '/' + nowArray.getFullYear()) + '</td><td> ' + lowTempArray[i] + '</td><td> ' + highTempArray[i] + '</td></tr>';
}
message += '</table>';
output.innerHTML = message;
}
}
}
}
return false;
}
function init() {
'use strict';
document.getElementById('theForm').onsubmit = process;
} // End of init() function.
window.onload = init;
The user should be able to enter in an integer and see the base, squared, and cubed result of that number. The base result should be listed under the "base" header, the squared result should be listed under the "squared" header and the cubed result should be listed under the "cubed" result. However, my output is listed all results under the "base" header. How can I make the results be listed under the related headers? This is what I have:
var $ = function (id) {
return document.getElementById(id);
}
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput;
for (var i = 1; i <= integer; i++) {
base += i + "\n";
squared += i * i + "\n";
cubed += i * i * i + "\n";
displayOutput = base + squared + cubed;
}
$("output").value = header + displayOutput;
}
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
}
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
}
It all depends on the output. Trying to stay as close as possible to your code, seems you are inserting your resulting displayOutput string into a textarea control. If you want to keep it that way, try tabs (\t) to separate your columns, and only a new line at the end (\n). Also, I noticed you were concatenating every column (base, square, and cubed) on every iteration, so I removed that. Here's the result:
var $ = function (id) {
return document.getElementById(id);
};
var calculate = function () {
//Get the input from the user and assign it to the userInput variable
var integer = $("integer").value;
var header = "Base" + " " + "Square" + " " + "Cubed" + "\n";
var squared = "";
var cubed = "";
var base = "";
var displayOutput = "";
for (var i = 1; i <= integer; i++) {
base = i + "\t";
squared = i * i + "\t";
cubed = i * i * i + "\n";
displayOutput += base + squared + cubed;
}
$("output").value = header + displayOutput;
};
var form_reset = function () {
$("output").value = "";
$("integer").value = "";
};
//Assign event handlers to their events
window.onload = function () {
$("powers").onclick = calculate;
$("clear").onclick = form_reset;
$("theform").onsubmit = function() { return false; };
};
Basically I have 5 words picked out of an array (English Words) And I pick 1 French word out of another array which the user then has to guess what that french word means in english.
At the moment I am adding the Correct English Answer to the end of the select menu because I don't know how to add it inbetween the others randomly, or more so to shuffle the select menus options
I Have added my JSfiddle below, It is an exact replica. You will realise that the bottom option is always correct! (The user will begin to know the pattern). I've also had to add my javascript below to be able to post the JSfiddle
http://jsfiddle.net/jamesw1/w8p7b6p3/5/
var
RanNumbers = new Array(6),
foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
//Generate random numbers to pick the available answers
function wordGen() {
for (var h = 0; h < RanNumbers.length; h++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[h] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 0; i < 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
var numGames = 5;
var numGuesses = 1;
var correct = 0;
var wrong = 0;
var prevNumber;
//On click, gather correct and wrong answers, create new numbers, create new options, create new word.
document.getElementById('submitAns').onclick = function () {
prevNumber = number;
number = Math.floor((Math.random() * 30)),
output = '',
correctAns = translate[number];
document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;
var
genWord = document.getElementById('generatedWord').textContent,
select = document.getElementById('guesses'),
selectedText = select.options[select.selectedIndex].text;
prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;
//Re doing the function, getting new values...
function wordGen() {
for (var j = 0; j < RanNumbers.length; j++) {
var temp = 0;
do {
temp = Math.floor(Math.random() * 30);
} while (RanNumbers.indexOf(temp) > -1);
RanNumbers[j] = temp;
}
}
//Call the previous function
wordGen();
//Create dynamic select menu
document.getElementById('generatedWord').textContent = foreignWords[number];
var guess = "<select name='guesses' id='guesses'>";
for (var i = 1; i <= 6; i++) {
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
guess += '<option value="6">' + correctAns + '</option>';
guess += "</select>";
document.getElementById('output').innerHTML = guess;
numGuessed = document.getElementById('guesses').value;
function arrayValueIndex(arr, val) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
return i;
}
}
return false;
}
//Checking of the answers below, Accumilating correct and wrong answer.
numGuesses++;
if (numGuesses == 6) {
document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
$('#submitAns').hide();
}
};
You should use Math.random method, it would be something like this:
var correctAnswerIndex = Math.floor(Math.random() * 7); //gives random number between 0-6
for (var i = 1; i <= 6; i++) {
if(i == correctAnswerIndex)
guess += '<option value="'+i+'">' + correctAns + '</option>';
else
guess += "<option value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";
}
you will need just to adjust else statement, as RanNumbers may not have 6 items. So maybe to introduce additional counter that would be used insead of i. (something like translate[RanNumbers[counter++]])