JavaScript Pagination Slice Array and create a button for every page - javascript

I have an Array of objects:
let myArray = {
{productName: "Product 1"},
{productName: "Product 2"},
{productName: "Product 3"},
{productName: "Product 4"},
{productName: "product 5"},
}
I have looped through this Array and dislpayed all of the objects using the following code:
for (let i of myArray) {
let paragraph = document.createElement("div");
paragraph.innerText = i.productName;
}
This has correctly dislpayed all of the objects.
I now want to paginate these objects. There should be 10 objects per page. However, all of the objects should be shown from the same web address/ HTML file.
This should be done using the Array.slice() method.
The first 10 objects should be sliced and displayed on the first page.
The next 10 objects should be sliced and displayed on the second page.
For every page created, a button should be created, which will point to the correct page.
I have tried using this code to create the pagination:
let first_element = 0;
let second_element = 11;
let button_number = 0;
let slice = products.slice(first, second);
for (let i of products) {
for (let i of slice) {
let paragraph = document.createElement("div");
paragraph.innerText = i.productName;
}
button_number += 1;
let button = document.createElement('button');
button.innerText = button_number;
document.getElementById("buttons").appendChild(button)
}
I expected this to display all of the items once, on seperate pages.
However, this displays the same object multiple times on the same page.

Related

retrieve elements from two-dimensional array

I have a quiz with 3-4 answer choices.
How can I retrieve them if the answer choices varies per question ?
I know code if I have the same number of choices for every question.
My code:
var answerArray = [
["black", "green", "yellow", "orange"],
["big","small","long"],
];
function wait() {
questionCounter < 1 ?
(questionCounter++,
generateQuestions(),
};
function generateQuestions() {
gameHTML = "<p class='text-center'>" + questionArray [questionCounter] + "</p><p class='first-answer answer'>A. " + answerArray[questionCounter][0] + "</p><p class='answer'>B. "+answerArray[questionCounter][1]+"</p><p class='answer'>C. "+answerArray[questionCounter][2]+"</p><p class='answer'>D. "+answerArray[questionCounter][3]+"</p>";
$("#mainArea").html(gameHTML);
};
You need to check the length of the answers array for that question and iterate over each answer:
function generateQuestions() {
const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
let gameHTML = "<p class='text-center'>;
// iterate over each answer:
answerArray[questionCounter].forEach((answer, index) => {
const letter = letters[index] + '.';
gameHTML += "<p class='answer'>" + letter + answer + "</p>"
})
$("#mainArea").html(gameHTML);
};
You should probably be using a loop for this even when you know the number, just to make the code more maintainable (like, so you don't have to rewrite the logic in case the number changes.)
For example, you could dynamically make a list of questions like this:
const questionsArray = [
["What's my favorite color?"],
["Describe my favorite toy."]
];
const mainContainer = document.querySelector("#mainContainer");
for(let i = 0; i < questionsArray.length; i++){
// Makes a node to hold the question text
let qTextNode = document.createTextNode(questionsArray[i]);
// Makes a paragraph element to display the question text in
let qParagraph = document.createElement("p");
// Makes a div element to hold this question and all its possible answers
let qContainer = document.createElement("div");
// Gives the container some distinguishing attributes
qContainer.classList.add("question");
qContainer.id = (i + 1);
// Puts the text in the paragraph
qParagraph.appendChild(qTextNode);
// Puts the paragraph in the container
qContainer.appendChild(qParagraph);
// Adds the container (and everything inside it) to the page
mainContainer.appendChild(qContainer);
}
// Prints out the HTML we just created
console.log(mainContainer.outerHTML.split("><").join(">\n<"));
<div id="mainContainer"></div>
It may not look like much when you run the snippet, but as you can see in the console, you now have an organized structure for all your answer choices to live in. Later javascript code can come along and find specific elements on your page, as can CSS styles.
Here's a juiced-up version that adds the answer text for each question. For this, we need a loop inside a loop (since each question has several answer choices that we want to add dynamically):
const questionsArray = [
["What's my favorite color?"],
["Describe my favorite toy."]
];
const answersArray = [
["black", "green", "yellow", "orange"],
["big","small","long"],
];
// Stuff you saw in the previous snippet
const mainContainer = document.querySelector("#mainContainer");
for(let i = 0; i < questionsArray.length; i++){
let qTextNode = document.createTextNode(questionsArray[i]);
let qParagraph = document.createElement("p");
let qContainer = document.createElement("div");
qContainer.classList.add("question");
qContainer.id = (i + 1);
qParagraph.appendChild(qTextNode);
qContainer.appendChild(qParagraph);
// Makes an "ordered list" element to hold the choices
let aList = document.createElement("ol");
// Letters array will be used for item IDs
let letters = "A,B,C,D,E,F,G,H,I,J".split(",");
// A nested loop to add the choices
for(let j = 0; j < answersArray[i].length; j++){
// Makes a textNode to hold the current choice
let aTextNode = document.createTextNode(answersArray[i][j]);
// Makes a list-item element to display the choice text in
let aItem = document.createElement("li");
// Gives the item an id using question number & answer letter
aItem.id = (i + 1) + letters[j];
// Puts the choice text in the item
aItem.appendChild(aTextNode);
// Puts the item in the list
aList.appendChild(aItem);
}
// Done looping through choices, this adds the list to the question container
qContainer.appendChild(aList);
// And... we're back to stuff from the previous snippet
mainContainer.appendChild(qContainer);
}
console.log(mainContainer.outerHTML.split("><").join(">\n<"));
/* The visible letters for the list items come from here, not from the script */
ol{ list-style-type: upper-alpha; }
.question{ margin-top: 25px; }
<div id="mainContainer"></div>

Loop over createElement in java script not executing completely

I am writing code for my e-commerce prototype website. I need to create a dynamic drop-down in one of pages in which it will receive drop-down values (like color here) from database and then I have to create drop-down using that.
I have written following code so far for this.
//Json object retrieved from database
var tmp = {"category_id":4,"product_available_quantity":20,"product_color":["Red","Blue","Yellow"],"product_condition":"new","product_description":"Branded Metal Body 4 Star","product_discount":0,"product_id":1,"product_img_url":"http://localhost:5224/ebaytester/images/s-l1600.jpg","product_name":"Motorola Cover","product_price":250,"product_shipping":"free","product_sold_quantity":10,"sub_category_id":7};
//dropdown code for color
var col_div = document.createElement('div');
col_div.className = "dropdown";
var col_btn = document.createElement('button');
var col_span = document.createElement("span");
col_span.className = "caret";
col_btn.className = "btn dropdown-toggle";
col_btn.setAttribute("type","button");
col_btn.setAttribute("data-toggle","dropdown");
text_node = document.createTextNode("Select");
col_btn.appendChild(text_node);
col_btn.appendChild(col_span);
col_div.appendChild(col_btn);
var ulst = document.createElement('UL');
ulst.className = "dropdown-menu";
var color = tmp['product_color'];
document.write(tmp['product_color'].length);
for(var i=0;i<tmp['product_color'].length;i++)
{
var list = createElement('li');
var anc = createElement('a');
text_node = createTextNode(tmp['product_color'][i]);
anc.setAttribute('href','#');
anc.appendChild(text_node);
list.appendChild(anc);
ulst.appendChild(list);
document.write(tmp['product_color'][i]);
}
col_div.appendChild(ulst);
document.getElementById("second").appendChild(col_div);
After tracking I finds out the problem is in for loop. As soon as it executes first createElement method it came out from loop abruptly. I have cross check all the syntax several times but all seems fine. I am using DOM(Document Object Model) first time so excuse me for mistakes and please tell me if I am doing something wrong.
Thanks
As soon as it executes first createElement method it came out from
loop abruptly.
Unless you have your own custom createElement method, your browser is likely to throw an error (check your dev-console) indicating that createElement method is undefined.
Replace it with document.createElement
or create your own createElement method as
function createElement( name )
{
return document.createElement( name );
}
your could be like this . if you want. problem with your create element method. this approach you can follow with appending with your class name etc.
var tmp = { "category_id": 4, "product_available_quantity": 20, "product_color": ["Red", "Blue", "Yellow"], "product_condition": "new", "product_description": "Branded Metal Body 4 Star", "product_discount": 0, "product_id": 1, "product_img_url": "http://localhost:5224/ebaytester/images/s-l1600.jpg", "product_name": "Motorola Cover", "product_price": 250, "product_shipping": "free", "product_sold_quantity": 10, "sub_category_id": 7 };
window.onload = function () {
//dropdown code for color
var div = document.querySelector("#container"),
frag = document.createDocumentFragment(),
select = document.createElement("select");
var options = tmp.product_color;
select.options.add(new Option("--Select--", "-1", true, true));
for (var i = 1; i < options.length;i++)
select.options.add(new Option(options[i], options[i]));
frag.appendChild(select);
div.appendChild(frag);
}
<div id="container">
</div>

choosing a random array from a list and move it to a different list

for my class assessment I'm doing a card game on app lab, so I made each card into a list of arrays and made the ace, jack, queen, and king as variables and also in the lists,
I'm trying to move a random array to another list that will be my hand for the card and I have been digging through the API but it doesn't tell me and I cant think of a way of doing it without it running an error. I'm still pretty new to coding so sorry if its not that good
here's my code so far
var A=1;
var J=11;
var Q=12;
var k=13;
var yourcards= [];
var AICards =[];
var chooseCard = randomNumber(0,51);
var cards = ["A", "2", "3","4","5","6","7","8","9","10","J","Q","K","A", "2", "3","4","5","6","7","8","9","10","J","Q","K","A", "2", "3","4","5","6","7","8","9","10","J","Q","K","A", "2", "3","4","5","6","7","8","9","10","J","Q","K"];
onEvent("War", "click", function(event) {
etScreen("gameGrounds");
});
function CardDeal(){
for (var i = 0; i < 25; i++) {
chooseCard();
}
}

Randomly selecting unique items from an array with Javascript

I know that there have been a lot of similar questions and I went through most of them. The code that is closest to what I'm trying to achieve is this one.
I have a list of people in each column (which represent a day). for the sake of this question let's assume it's 8 people in each column. I need to randomly select 5 unique people names. I've used splice() to delete the selected item from the array to make sure that it is not selected twice. I'm new to the coding and I think I'm doing some basic mistake as the splice works for the 1st loop and then the array goes back to the original one. Can you, please, help to identify my mistake?
for (var x = 0; x < 5; x++) {
var sourceArray = ss.getRange(49,j+5,8,1).getValues();
var gg = Math.floor(Math.random()*sourceArray.length);
var pickedHLA = sourceArray[gg];
sourceArray.splice(gg, 1);
var HLAselect = ss.getRange(30+x,j+5,1,1)
HLAselect.setValue(pickedHLA);
In your for loop you are redefining the sourceArray during each iteration - you need to define this outside the loop, then do your work to randomly select and remove from the array:
var sourceArray = ss.getRange(49,j+5,8,1).getValues(); //establish full list of people
for (var x = 0; x < 5; x++) {
var gg = Math.floor(Math.random()*sourceArray.length); //get random index
var pickedHLA = sourceArray[gg]; //get random person via random index
sourceArray.splice(gg, 1); //remove random person from full list of people
var HLAselect = ss.getRange(30+x,j+5,1,1)
HLAselect.setValue(pickedHLA);
}
The way you do this is actually quite simple, all it requires a few lines of code:
var arr = ["Cheese", "Purple", "List", "1", "2", "3", "4", "5"];
function random() {
var randomNumber1 = parseInt(Math.random() * arr.length);
var random = arr[randomNumber1];
alert(random);
}
<button onClick="random()">Click Me</button>
There you go!

create div with content from array of objects?

So I have:
arrayofobj = [
{
property: "string", // "card" object with different data types
property2: integer
},
{
property: "string", // "card" object with different data types
property2: integer
},
{
//etc more cards
}
];
var playDeck = arrayofobj.slice(0);//creates copy of deck to "use" for game
shuffled(playDeck);//shuffles deck
playerHand = [];//empty array to save cards into
deal10(playDeck);//removes the 1st 10 out of playDeck and puts in playerHand
Now from the 10 that get drawn into playerHand, I'm trying to display them on screen. I have a field set up with:
<div id="playerHand"></div>
My attempt which hasn't been very successful:
for (var i = 0; i < playerHand.length; i++) {
content = playerHand[i];
x = document.getElementById('playerHand').appendChild(document.createElement('div'));
x.className = 'card' + [i];
document.getElementsByClassName('card' + [i]).textContent = content;
}
I haven't been able to achieve the desired effect. I'm a beginner as far as programming goes so I'm open to constructive criticism. So if you haven't gathered already what I'm trying to do is display each object or card on the screen as its own div (so that I can add click handlers to them and have the clicked one played on the screen... for example.)
I think the main problem is getElementsByClassName, which returns an array and not the actual reference to the element. See below:
var data, content, container, element;
container = document.getElementById('container');
data = [
{
name: "stringa"
},
{
name: "stringb"
}
];
for (var i = 0; i < data.length; i++) {
// Are you accessing an actual property in your code? It seems
// you are just referencing the whole object.
content = data[ i ].name;
// Just save the createElement reference ;)
element = document.createElement('div');
// Why are you appending [i] instead of i directly?
element.className = 'card' + i;
// By saving the element directly we don't have to query for
// the class in this step. The other problem was probably that
// `getElementsByClassName` returns an array, so you would have
// to call: vvv
// document.getElementsByClassName('card' + [i])[ 0 ]
element.textContent = content;
container.appendChild( element );
}
Obligatory JSFiddle: http://jsfiddle.net/tgtefsrm/1/

Categories

Resources