Comparring Arrays with For Loops - javascript

Alright so I have been working on this one for a bit. I'm comparing the values of two arrays using a For Loop. Every time the array known as cart hits a number that can be found in the products array, it displays the info of the products array, for each time it is hit. I think my code itself is fine ( though I could be wrong) but it's not displaying the values. So I think there's something wrong with my execution of said process there. The codes as follows
function Fill(){
var txt=""
var products = new Array();
products[0] = {name: "refrigerator" , price:88.99, img:"img/refrigerator.jpg"};
products[1] = {name: "microwave oven" , price: 76.99 , img:"img/microwave.jpg"};
products[2] = {name: "dishwasher" , price:276.67 , img:"img/dishwasher.jpg"};
var carts = new Array ();
carts[0]= 2;
carts[1]= 0;
carts[2]= 1;
carts[3]= 1;
carts[4]= 0;
carts[5]= 1;
carts[6]= 2;
carts[7]= 2;
for(var i=0; i < carts.length; i++){
for(var j = 0; j < products.length; j++){
if(carts[i] == j){
txt +=products[j].name + ' ' + products[j].price +" <img src='"+ products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
}

Update answer with ES6:
const products=[{name:"refrigerator",price:88.99,img:"img/refrigerator.jpg"},{name:"microwave oven",price:76.99,img:"img/microwave.jpg"},{name:"dishwasher",price:276.67,img:"img/dishwasher.jpg"}];
const carts=[2,0,1,1,0,1,2,2];
const productsInCart = [...new Set(carts)]
.reduce((a,c)=>{
a.set(c,products[c])
return a;
}, new Map());
const res = carts.map(c=>{
const {name, price, img} = productsInCart.get(c)
return `${name} ${price} <img src="${img}"/>`;
}).join("");
document.body.innerHTML = res;
You should be comparing carts[i] with j otherwise you won't find anything
var txt = ""
var products = new Array();
products[0] = {
name: "refrigerator",
price: 88.99,
img: "img/refrigerator.jpg"
};
products[1] = {
name: "microwave oven",
price: 76.99,
img: "img/microwave.jpg"
};
products[2] = {
name: "dishwasher",
price: 276.67,
img: "img/dishwasher.jpg"
};
var carts = new Array();
carts[0] = 2;
carts[1] = 0;
carts[2] = 1;
carts[3] = 1;
carts[4] = 0;
carts[5] = 1;
carts[6] = 2;
carts[7] = 2;
for (var i = 0; i < carts.length; i++) {
for (var j = 0; j < products.length; j++) {
if (carts[i] == j) {
txt = products[j].name + ' ' + products[j].price + " <img src='" + products[j].img + "'>"
document.getElementById("answer").innerHTML += txt
}
}
}
<div id="answer"></div>
Your txt variable should be modified with = and not +=
You should optimize your code. document.getElementById("answer") could be initiated globally for example.

"carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.

What's the value of your appliance variable?
It'll cause the code to error out.
To also steal Alex's answer: "carts" is an array of numbers (as per your source code) while "products" is an array of objects. So your condition "carts[i] == products[j]" will never fire.
Perhaps this is better?..
carts[7]= 2;
for(var i=0; i < carts.length; i++){
txt +=products[carts[i]].name + ' ' + products[carts[i]].price +" <img src='"+ products[carts[i]].img + "'>"
document.getElementById("answer").innerHTML += txt
}
Upvoting Grimbode's answer as it's pretty close to mine, but cleaner.

I'm not sure why you need the second for loop. You're trying to compare a number with a product object by doing this and it will never work. OK, assuming that what you are trying to achieve is that if carts[0]=2 you want the info for products[2] then try something like:
for(i=0; i<carts.length; i++) {
if(i<products.length) {
currProd=products[carts[i]];
//Process the currProd object as you will
}
}

Related

How to set [i] in array?

I don't know to set [i] in the array.
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus[fs_+ i +_P41001_W41001B]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse.fs_ +
[i] +_P41001_W41001B.data.gridData.rowset[0].sDescription_99.value
});
}
}
You could change:
dataStatus[fs_+ i +_P41001_W41001B]
to
dataStatus["fs_" + i + "_P41001_W41001B"]
Explaination
This is roughly how the computer understands it the following line:
Take string "fs_"
Add the variable i to it, so the string become "fs_4" (if i = 4)
Add "_P41001_W41001B" to it, so the string becomes "fs_4_P41001_W41001B"
Get dataStatus["fs_4_P41001_W41001B"]
Updated code:
statusResponse() {
var dataStatus = this.$.xhrStatus.lastResponse;
for(var i = 0; i < this.maxStatus; i++) {
console.log(this.maxStatus);
console.log([i]);
console.log(dataStatus);
console.log(dataStatus["fs_" + i + "_P41001_W41001B"]);
this.userInfo.status({
"branch_plant": this.$.xhrStatus.lastResponse["fs_" + i + "_P41001_W41001B"].data.gridData.rowset[0].sDescription_99.value
});
}
}

Triva Game, compare radio buttons value to answer

I'm creating a Trivia game using an array of objects. I created a function that loops through and displays all the questions and then loops through all the choices and turns them into radio buttons. I've been struggling comparing the answer to the selected value, so when the timer runs out I can print how many the user got right and wrong. Can someone point me to correct direction?
function countdown() {
var counter = 60;
var timeCountdown = setInterval(function(){
counter--
$('.timer-container .time').html(counter);
if (counter === 0) {
clearInterval(timeCountdown);
$('.timer-container .time').html("Times Up");
points();
}
}, 1000);
$('.timer-container').toggle();
}
let trivia = [
{
question: "How many wheels are on a skateboard?",
choices: ["2", "4", "6", "8"],
answer: "2",
},
{
question: "Who invented the kickflip?",
choices: ["Tony Hawk", "Bam Magera", "Rodney Mullen", "Chad Muska"],
answer: "Rodney Mullen"
},
{
question: "Who did the first 900?",
choices: ["Tony Hawk", "Tas Pappas", "Danny Way", "bob burnquist"],
answer: "Tony Hawk",
},
{
question: "What is another word for a 360 flip?",
choices: ["Impossible Flip", "3 1/2 flip", "Tre Bomb", "Tri Flip"],
answer: "Tre Bomb",
}
];
function triviaQuestions() {
for(var i = 0; i < trivia.length; i++) {
var questionHeader = $('<h2 class="question-' + i + '">');
var questionHeaderContent = questionHeader.text(trivia[i].question);
$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + " '>");
for (var j = 0; j < trivia.length; j++) {
console.log(trivia[i].choices[j]);
var questionChoices = $('<input type="radio"' + 'name="' + i + '"'+ 'value="' + trivia[i].choices[j] + '">' + '<label>' + trivia[i].choices[j] + '</label>');
var questionChoicesContent = questionChoices.text(trivia[i].choices[j]);
$('.choices-container-' + i).append(questionChoices).append(questionChoicesContent);
}
}
}
$( document ).ready(function() {
$('.start-button').on('click', function() {
$(this).toggle();
countdown();
triviaQuestions();
});
});
Thanks
Your points() function could look something like this:
function points() {
var correct = 0;
$(".choices").each(function(i){
var questionid = $(this).attr('id').split('-')[1];
var answer = $(this).find("input:checked").val();
if (answer == trivia[questionid].answer) correct += 1;
});
$(".points-container").toggle();
$(".points-container span").text(correct);
}
assuming you have an element somewhere on your page like this:
<div class="points-container" style="display:none">Total Points: <span></span></div>
and assuming you add the id="" attibute to your form elements:
$('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + "' id='choices-" + i + "'>");
The function above loops through each form on your page, pulls the question's index in the trivia array from the form's id, and matches the answer given against the answer specified in that index. Perhaps not the most elegant solution, but it worked for me, with minimal edits to your code.
There's a bit going on here so I've given you a complete solution - this covers the timer, the printing of the question/answer sets and the testing functionality.
A complete codepen here: https://codepen.io/V3Dev/pen/vYBaEVL
Details below - enjoy :)
HTML
<input id="trigger" type="button" value="Start Timer" onclick="startTimer();"/>
<p id="timer">60 Seconds Remaining</p>
<br>
<input id="trigger" type="button" value="Test Answers Immediately" onclick="testAnswers();"/>
<br><br><br>
<div id="container"/>
Script
//starting JSON
let trivia = [*JSON*];
//iterate over your JSON
for (let i = 0; i < trivia.length; i++) {
//print the question
document.getElementById("container").appendChild(document.createTextNode(trivia[i].question));
document.getElementById("container").appendChild(document.createElement("br"));
//iterate over the choices and create answer objects
for (let i2 = 0; i2 < trivia[i].choices.length; i2++) {
//print the choices
var input = document.createElement("input");
input.type = "radio";
input.value = trivia[i].choices[i2];
input.name = trivia[i].question;
document.getElementById("container").appendChild(input);
document.getElementById("container").appendChild(document.createTextNode(trivia[i].choices[i2]));
document.getElementById("container").appendChild(document.createElement("br"));
};
//seperate questions
document.getElementById("container").appendChild(document.createElement("br"));
document.getElementById("container").appendChild(document.createElement("br"));
};
//test the submitted answer against the stored value
function testAnswers(){
let score = 0;
for (let i = 0; i < trivia.length; i++) {
let questionSelectedAnswer = getRadioValue(trivia[i].question);
if (questionSelectedAnswer == trivia[i].answer){
score++;
}
}
alert("You scored " + score + "/" + trivia.length);
}
//get the selected value for a collection of answers
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
//set the timer logic
var timer;
function startTimer() {
//clear any running timers
clearInterval(timer);
var secondsRemaining = 60;
timer = setInterval(function() {
secondsRemaining--;
// If the count down is over run the test
if (secondsRemaining < 1) {
clearInterval(timer);
testAnswers();
secondsRemaining = 0;
}
//print the time
document.getElementById("timer").innerHTML = secondsRemaining + " seconds remaining";
}, 1000);
}

Add alphabets dynamically as html row increments

How to ensure i have a dynamic increment of Alphabets in a new cell on left side, next to each cell in a row which is dynamically created based on the option chosen in Select. This newly generated alphabet will be considered as bullet points/serial number for that particular row's text box.
jsfiddle
js code
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
html
<select id="Number_of_position">
</select> <table id="Positions_names">
</table>
This is essentially a base26 question, you can search for an implementation of this in javascript pretty easily - How to create a function that converts a Number to a Bijective Hexavigesimal?
alpha = "abcdefghijklmnopqrstuvwxyz";
function hex(a) {
// First figure out how many digits there are.
a += 1; // This line is funky
var c = 0;
var x = 1;
while (a >= x) {
c++;
a -= x;
x *= 26;
}
// Now you can do normal base conversion.
var s = "";
for (var i = 0; i < c; i++) {
s = alpha.charAt(a % 26) + s;
a = Math.floor(a/26);
}
return s;
}
So you can do
$(document).ready(function(){
var select = $("#Number_of_position"), table = $("#Positions_names");
for (var i = 1; i <= 100; i++){
select.append('<option value="'+i+'">'+i+'</option>');
}
select.change(function () {
var rows = '';
for (var i = 0; i < $(this).val(); i++) {
rows += "<tr><td>" + hex(i) + "</td><td><input type='text'></td></tr>";
}
table.html(rows);
});
});
Heres the example http://jsfiddle.net/v2ksyy7L/6/
And if you want it to be uppercase just do
hex(i).toUpperCase();
Also - this will work up to any number of rows that javascript can handle
if i have understood you correctly, that's maybe what you want:
http://jsfiddle.net/v2ksyy7L/3/
I have added an array for the alphabet:
var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
and then added the output to your "render" loop:
rows += "<tr><td>" + alphabet[i] + " <input type='text'></td></tr>";

dat.GUI create multiple buttons with same name

I try to use dat.GUI to create multiple buttons all with same name "ShowCoord", is this possible? What I have currently is:
for (i = 0; i < overlay.numElements; i ++)
{
var length = overlay.elementNumVertices[i];
var subObj = {
'name' : overlay.elementNames[i],
'index' : i,
'numVertices': overlay.elementNumVertices[i],
"ShowCoord" : function(){
console.log("i is " + subObj['index']);
var verts = overlay.elementVertices[i];
for(var j = 0; j < subObj['numVertices']; j ++)
{
console.log("The coordinates are " + verts[3*j] + ", "+ verts[3*j+1] +", "+verts[3*j+2]);
}
}
};
subObjArray.push(subObj);
}
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
var subGui = gui.addFolder(currObj['name']);
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
I now have the correct currObj['name'] and currObj['numVertices'] displayed. But all the "ShowCoord" button only contains information of the very last subObj (so console.log("i is " + subObj['index']) will print out 148 every time even if I click different button). How can I make it work? Thanks a lot!
Try moving subGui outside the for loop and modifiy you code so that you don't reassign subGui varialbe.
var subGui = new dat.GUI();
for(i = 0; i < subObjArray.length; i ++)
{
var currObj = subObjArray[i];
subGui.addFolder(currObj['name']);// <--- work on this line
subGui.add(currObj, 'numVertices');
subGui.add(currObj, "ShowCoord");
}
Otherwise it will always be redefined with the last iterated element of for loop
Note: This is just a hint, I can't conclude more from your code.

Changing radio buttons name using Javascript

I'm using a simple JS duplicate function to duplicate a div. Inside is form information with radio buttons, including one group called 'getOrRequest'. Each div represents a book and needs to have its own 'getOrRequest' value.
The name needs to be changed in order to make each duplicated group of radio buttons selectable without affecting every other radio button. What is the best way to change these values?
Here is how I'm duplicating the div, in case that is the issue.
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
bookInfo.appendChild(copyDiv);
I then have tried a couple methods of changing the name value. Like this:
bookInfo.copyDiv.getOrRequest_0.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
bookInfo.copyDiv.getOrRequest_1.setAttribute("name", "'getOrRequest' + idNumber + '[]'");
As well as this:
bookInfo.copyDiv.getOrRequest_0.name = 'getOrRequest' + idNumber + '[]';
bookInfo.copyDiv.getOrRequest_1.name = 'getOrRequest' + idNumber + '[]';
getOrRequest_0 and getOrRequest_1 are the ID's of the input values, but I've tried it a few ways now and nothing seems to work. Thanks in advance!
EDIT: MORE INFO
Here is the specific code I'm using:
function addAnotherPost(){
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = 'addListing' + idNumber;
for(var j = 0; j < size; j++){
if(copyDiv.childNodes[j].name === "getOrRequest[]"){
copyDiv.childNodes[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
And it just doesn't seem to work.. The divs are duplicating, but the name value is not changing.
You can try this - http://jsfiddle.net/ZKHF3/
<div id="bookInformation">
<div id="addListing">
<input type="radio" name="addListing0[]" />
<input type="radio" name="addListing0[]" />
</div>
</div>
<button id="button">Add Listing</button>
<script>
document.getElementById("button").addEventListener("click", AddListing, false);
var i = 1;
var bookInfo = document.getElementById('bookInformation');
function AddListing() {
var copyDiv = document.getElementById('addListing').cloneNode(true);
var size = copyDiv.childNodes.length;
copyDiv.id = "listing" + i;
for ( var j = 0; j < size; j++ ) {
if ( copyDiv.childNodes[j].nodeName.toLowerCase() == 'input' ) {
copyDiv.childNodes[j].name = "addListing" + i + "[]";
}
}
bookInfo.appendChild(copyDiv);
i++;
}
</script>
The trouble is you are looking for child nodes of the div, but the check boxes are not child nodes, they are descendant nodes. The nodes you are looking for are nested within a label. Update your code to look for all descendant inputs using copyDiv.getElementsByTagName("input"):
var idNumber = 0;
function addAnotherPost() {
var bookInfo = document.getElementById('bookInformation');
var copyDiv = document.getElementById('addListing').cloneNode(true);
copyDiv.id = 'addListing' + idNumber;
var inputs = copyDiv.getElementsByTagName("input");
for(var j = 0; j < inputs.length; j++){
if(inputs[j].name === "getOrRequest[]"){
inputs[j].name = "getOrRequest" + idNumber + "[]";
}
}
bookInfo.appendChild(copyDiv);
idNumber++;
}
http://jsfiddle.net/gilly3/U5nsa/

Categories

Resources