Desired:
In class Games, there is a column named RoundWinners that contains arrays filled with multiple UserId. For each Round that a player wins, their UserId is added to the array:
The front-end displays a list displaying each Game in the DB. For each Game, I want to count the number of rounds the current user, currentUserId, has won, and display this number as userScore.
Example:
Current User: Bob
Game 1, Score = 2:
["Bob", "Sue", "Joe", "Bob"]
Game 2, Score = 1:
["Bob", "Lahkim"]
Game 3, Score = 0:
["John", "Mark", "Ronnie", "Alice"]
Code:
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
userScores.push(userScore);
};
};
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
Current Error:
The first game displays a userScore of 1, although the current user hasn't won any rounds, and all subsequent games display "undefined".
You have to use 2 for loops for this...
var roundWinners = [["Bob", "Sue", "Joe", "Bob"],["Bob", "Lahkim"],["John", "Mark", "Ronnie", "Alice"]];
var gameIds = [1,2,3];
var currentUserId = "Bob";
var userScore;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
userScore = 0;
for (j=0; j < roundWinners[i].length; j++){
if (roundWinners[i][j] == currentUserId) {
userScore++;
}
}
userScores.push(userScore);
}
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='BottomContainer'>" + userScores[i] + "</div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
<div id="games"></div>
The reason that you are always getting 1 as the userScore is because you're pushing the userScore into userScore each time you find a match. Instead, you should loop through all the roundWinners, count the number of times the currentUserId appears, and then push to the array of userScores. I have edited your code below with a comment indicating the change.
var userScore = 0;
var userScores = [];
for (i = 0; i < roundWinners.length; i++) {
if (roundWinners[i] == currentUserId) {
userScore++;
};
};
//Push to userScores AFTER you finish going through all of the round winners
userScores.push(userScore);
var numberOf = gameIds.length;
var text = "<ul>";
for (i = 0; i < numberOf; i++) {
text += "<div class='GameContainer'> + userScores[i] + </div>";
text += "</li>";
}
text += "</ul>";
//Ammend HTML
document.getElementById("games").innerHTML = text;
Related
I have array like the below
data = [
[product, billdetail],
[avn, 200],
[plioc,3000],
[myjio,4000]
]
for(var i = 1; i < data.length; i++) {
var cube = data[i];
for(var j = 0; j < cube.length; j++) {
console.log("cube[" + i + "][" + j + "] = " + cube[j]);
if(cube[j] === "")
{
alert('empty value');
}
}
}
I am doing empty validation here, i also want validation like product should have only alphabets and billdetail should have number only.so how can i achieve that here.please help me for the same.
(consider first row is table header and other rows are values.)
There are many ways to do this, one of is below.
data = [
['product', 'billdetail'],
['avn', 213],
['plioc',3000],
['myjio',4000],
['inval1d produc1', 'invalidbill']
]
for (let i = 1; i < data.length; i++) {
let product = data[i][0];
let bill = data[i][1];
if (!product || !bill) {
console.log('Product or Bill is null', product, bill);
}
if (!product.match(/^[A-Za-z]+$/)){
console.log('Invalid Product:', product);
}
if (typeof(bill) !== 'number') {
console.log('Invalid Bill:', bill);
}
}
I would like to know how to append to the DOM just once after these nested loops.
Also, the variable letters is dynamic, so I would need to 'reset' my appended grid when a new string is passed to letters
let letters = "abcdefghijkl"
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`
);
}
}
Thank you in advance!
EDIT
After the answer from T.J. Crowder I tried to incorporate my code to be able to populate my grid from the inputs, but when I unselect one of the inputs, that row isn't cleared.
let letters = 'abcdefghijkl';
let html = "";
$(".list-checkbox-item").change(function() {
let chosenLetters = $(this).val();
if ($(this).is(":checked")) {
arrayOfChoices.push(chosenLetters);
} else {
arrayOfChoices.splice($.inArray(chosenLetters, arrayOfChoices), 1);
}
letters = arrayOfChoices.sort().join(""); // Gives me a string with chosen letters ordered alphabetically
console.log(
`This is my string in var 'letters' ordered alphabetically (Need to clear grid after each instantiation or append after the loop): %c${letters}`,
"color: red; font-weight: bold; font-size: 16px"
);
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html += `<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
});
What am I doing wrong?
Assuming #music-grid is empty before you run this code the first time, build up the HTML in a string and then use html() to replace the contents of #music-grid rather than appending to it:
let html = "";
for (let i = 0; i < letters.length; i++) {
var musicRowID = `${letters.charAt(i)}01`;
html += `<div id="music-row-${musicRowID}" class="row no-gutters">`; // *** No `</div>` yet
for (let j = 1; j <= 12; j++) {
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
html +=
`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`;
}
html += "</div>";
}
$("#music-grid").html(html);
You also see people building up the HTML in an array and using array.join("") at the end to get a single string, but with modern JavaScript engines it's really a wash either way...
Our developer used this phone number 1-866-579-469 all over the website but the correct phone number is 1-866-579-4269. I have written a javascript function to replace all occurrences:
var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) {
count = 0
for (var i = 0; i < nodes.length; i++) {
currentElement = nodes[i].innerHTML;
replaced = currentElement.replace(oldtext,newtext);
count++;
}
console.log("Edited: "+ count + " items");
}
oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');
replaceAll(nodes,oldtext,newtext,replaced);
Your code works but you missed to update the replaced string. This should work:
var nodes,currentElement,oldtext,newtext,replaced,count;
function replaceAll(nodes,oldtext,newtext,replaced) {
count = 0
for (var i = 0; i < nodes.length; i++) {
currentElement = nodes[i].innerHTML;
replaced = currentElement.replace(oldtext,newtext);
nodes[i].innerHTML = replaced;
count++;
}
console.log("Edited: "+ count + " items");
}
oldtext = "1-866-579-469";
newtext = "1-866-579-4269";
nodes = document.getElementsByTagName('*');
replaceAll(nodes,oldtext,newtext,replaced);
Codepen Here
I'm just learning now. Can you please help me, why am I not getting the correct output. This is my code:
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
var oList = "<ol>";
//function to print the result in ordered list
function printResult(result){
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[i] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML = message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
I have watched this code over and over again and I still can't understand why am I getting undefined as a result. In the debugger, after the loop I check my vars and everything seems ok.
In your printResult function you are using var i instead of j,
Also you better use innerHtml+=message;
//ask questions
var quiz = [
["When is Bulgaria established?", 681],
["What year was it before 16 years?", 2000],
["When does WWII ends?", 1945]
];
//variables
var answer = [];
var correct = [];
var wrong = [];
var correctAns = 0;
var wrongAns = 0;
//function to print the result in ordered list
function printResult(result){
//HERE:
var oList = "<ol>";
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message;
}
//looping, adding correct and wrong answeres
for(var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if(parseInt(answer[i]) == quiz[i][1]){
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if(correct.length < 1 || correct == undefined){
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1){
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if(wrongAns > 0){
print(printResult(wrong));
}
}
<div id="output">
</div>
Basically you have three problems.
reuse of oList, the variable should be inside declared and used only in printResult.
Inside of printResult, use of i where j have been used and
At print, you replace the actual content with new content.
Just a small hint with variable names for counting. It is good practise to start always with i instead of j and go on with the letters in the alphabet.
var quiz = [["When is Bulgaria established?", 681], ["What year was it before 16 years?", 2000], ["When does WWII ends?", 1945]],
answer = [],
correct = [],
wrong = [],
correctAns = 0,
wrongAns = 0;
//function to print the result in ordered list
function printResult(result) {
var oList = "<ol>"; // !!! move variable inside of the function
for (var j = 0; j < result.length; j++) {
oList += "<li>" + result[j] + "</li>"; // !!! use j indstead if i
}
oList += "</ol>";
return oList;
}
function print(message) {
document.getElementById('output').innerHTML += message; // !!! append message
}
//looping, adding correct and wrong answeres
for (var i = 0; i < 3; i++) {
answer[i] = prompt(quiz[i][0]);
if (parseInt(answer[i]) == quiz[i][1]) {
correct.push(quiz[i][0]);
correctAns++;
} else {
wrong.push(quiz[i][0]);
wrongAns++;
}
}
//print logic
if (correct.length < 1 || correct == undefined) {
print("You did not guess any of the quiestions!");
} else if (correct.length >= 1) {
print("You have guessed " + correctAns + " questions.");
print(printResult(correct));
print("You have " + wrongAns + " wrong answeres.");
if (wrongAns > 0) {
print(printResult(wrong));
}
}
Your main mistake is using i intead of j:
for(var j = 0; j < result.length; j++){
oList += "<li>" + result[j] + "</li>";// here was i before
}
I wrote this code in my html site, in Javascript, but is not working right. Most times it seems to ignore some entries and just randomly selects which is the min/max value. Also, when I tried to calculate average values, I got a string instead of a number, even though the variable is declared as 0 in the beginning. e.g performing 0+1+1+2+3+5 = 011235 instead of 12.
Here is the code, thanks in advance.
**EDIT: I added the student average code in the end, but it doesn't work, it doesn't show any results on the page, not even the "student" + [i] part. On the other hand, the parseInt() command worked, and made everything work as it should, thank you :)
<script language = "javascript">
function myFunction() {
var course0 = [];
var course1 = [];
var course2 = [];
var minstugrade = 100;
var maxstugrade = 0;
var minstugradetext = "";
var maxstugradetext = "";
var stuavgarr = [];
var minstuavg = 100;
var maxstuavg = 0;
var minstuavgtext = "";
var maxstuavgtext = "";
var mincougrade = 100;
var maxcougrade = 0;
var mincougradetext = "";
var maxcougradetext = "";
var mincouavg = 100;
var maxcouavg = 0;
var mincouavgtext = "";
var maxcouavgtext = "";
var couavg = 0;
//add form items to array
var x = document.getElementById("course0");
var i;
for (i = 0; i < x.length ;i++) {
course0.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course1");
var i;
for (i = 0; i < x.length ;i++) {
course1.push(parseInt(x.elements[i].value));
}
var x = document.getElementById("course2");
var i;
for (i = 0; i < x.length ;i++) {
course2.push(parseInt(x.elements[i].value));
}
//calculate course & student min/max
for (i = 0; i < course0.length; i++) {
if (course0[i] < mincougrade) {
mincougrade = course0[i];
mincougradetext = "course0";
}
if (course0[i] > maxcougrade) {
maxcougrade = course0[i];
maxcougradetext = "course0";
}
if (course0[i] < minstugrade) {
minstugrade = course0[i];
minstugradetext = "student" + [i];
}
if (course0[i] > maxstugrade) {
maxstugrade = course0[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course1.length; i++) {
if (course1[i] < mincougrade) {
mincougrade = course1[i];
mincougradetext = "course1";
}
if (course1[i] > maxcougrade) {
maxcougrade = course1[i];
maxcougradetext = "course1";
}
if (course1[i] < minstugrade) {
minstugrade = course1[i];
minstugradetext = "student" + [i];
}
if (course1[i] > maxstugrade) {
maxstugrade = course1[i];
maxstugradetext = "student" + [i];
}
}
for (i = 0; i < course2.length; i++) {
if (course2[i] < mincougrade) {
mincougrade = course2[i];
mincougradetext = "course2";
}
if (course2[i] > maxcougrade) {
maxcougrade = course2[i];
maxcougradetext = "course2";
}
if (course2[i] < minstugrade) {
minstugrade = course2[i];
minstugradetext = "student" + [i];
}
if (course2[i] > maxstugrade) {
maxstugrade = course2[i];
maxstugradetext = "student" + [i];
}
}
//calculate course average
for (i = 0; i < course0.length; i++) {
couavg += course0[i];
}
couavg = couavg / course0.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course0";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course0";
}
couavg = 0;
for (i = 0; i < course1.length; i++) {
couavg += course1[i];
}
couavg = couavg / course1.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course1";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course1";
}
couavg = 0;
for (i = 0; i < course2.length; i++) {
couavg += course2[i];
}
couavg = couavg / course2.length
if (couavg < mincouavg) {
mincouavg = couavg;
mincouavgtext = "course2";
}
if (couavg > maxcouavg) {
maxcouavg = couavg;
maxcouavgtext = "course2";
}
//calculate student average
for (i = 0; i < course0.length; i++) {
stuavgarr[i] += course0[i];
stuavgarr[i] += course1[i];
stuavgarr[i] += course2[i];
}
for (i=0; i < stuavgarr.length; i++) {
stuavgarr[i] = stuavgarr[i] / course0.length;
if (stuavgarr[i] < minstuavg) {
minstuavg = stuavgarr[i];
minstuavgtext = "student" + [i];
}
if (stuavgarr[i] > maxstuavg) {
maxstuavg = stuavgarr[i];
maxstuavgtext = "student" + [i];
}
}
document.getElementById("studmaxgrade").innerHTML = "Student that achieved the max grade is " + maxstugradetext
document.getElementById("studmingrade").innerHTML = "Student that achieved the min grade is " + minstugradetext
document.getElementById("studmaxavg").innerHTML = "Student that achieved the max average is " + maxstuavgtext
document.getElementById("studminavg").innerHTML = "Student that achieved the min average is " + minstuavgtext
document.getElementById("courmaxgrade").innerHTML = "The course in which the max grade is scored is " + maxcougradetext
document.getElementById("courmingrade").innerHTML = "The course in which the min grade is scored is " + mincougradetext
document.getElementById("courmaxavg").innerHTML = "The course in which the max average grade is scored is " + maxcouavgtext
document.getElementById("courminavg").innerHTML = "The course in which the min average grade is scored is " + mincouavgtext
}
</script>
The value of an input is a string, thus a + b will be interpreted as appending one string to another.
If you make sure the first parameter (a in this case) is an integer a + b will result in the two being mathematically adding the two
console.log( '0' + 1 + 2 + 3 + 4 ); //* outputs 01234
console.log( parseInt( 0 ) + 1 + 2 + 3 + 4 ); //* outputs 10
JSFiddle
Ok for a start you seem very confused about
document.getElementById
This does not address a javascript variable at all......
This literally "gets the document element by its id".
Here is an example of how to use it...
<html>
<img id='my_new_selfie' src='me.jpg'>
....
....
<script>
alert (document.getElementById('my_new_selfie').src)
</script>
This would simply pop up an alert with the text that describes the src of the
document object who's id is 'my_new_selfie'
that is....
[me.txt]
The reason that document.getElementById was introduced to javascript was to save developers learning the DOM (document object model) in order to access objects.
It allows you to simply give you object an id and change things about it using the id
In the above example I could use a script or button to change the image source
an example of this might be using the onclick event of another object on the page like a button...
onclick='document.getElementById('my_new_selfie').src='new_pic_of_me.JPG'
It is not used to identify variables in a javascript