I'd like to randomize my HTML-output with multiple elements within my for-loop:
var h = document.getElementById("test_block");
for(i = 0; i < 7; i++) {
h.insertAdjacentHTML("afterend", "<div class='one_hour onesy'><p>Foo</p></div>");
}
With a random output within the forloop of:
<div class='one_hour onesy'><p>Foo</p></div>
<div class='two_hour onesy'><p>Loo</p></div>
<div class='three_hour onesy'><p>Too</p></div>
So I'd like to get the adjacented HTML to be randomly one of these lines.
How can I do that?
Lets see if this helps:
var results = [
'<div class="one_hour onesy"><p>Foo</p></div>',
'<div class="two_hour onesy"><p>Foo</p></div>',
'whatever',
...
];
for(i = 0; i < 7; i++) {
h.insertAdjacentHTML("afterend", results[Math.floor((Math.random() * results.length))]);
}
Related
I have a for loop that is generating some HTML content:
var boxes = "";
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
}
document.getElementById("id").innerHTML = boxes;
I want to display 3 boxes in one row, then below them 2 boxes in one row, then 1, then 3 again, 2, and 1.
First i thought of using the if statement to check whether i > 2 to add a line break, but it will also add a line break after every box past the third one. Nothing comes to mind, and my basic knowledge of javascript tells me I'll have to make a loop for each row I want to make. Any advice?
I would use a different approch :
Use a array to store the number of item per row :
var array = [3, 2, 1, 3, 2];
Then, using two loops to iterate this
for(var i = 0; i < array.length; i++){
//Start the row
for(var j = 0; j < array[i]; ++j){
//create the item inline
}
//End the row
}
And you have a pretty system that will be dynamic if you load/update the array.
PS : not write javascript in a while, might be some syntax error
Edit :
To generate an id, this would be simple.
create a variable that will be used as a counter.
var counter = 0;
On each creating of an item, set the id like
var id = 'boxes_inline_' + counter++;
And add this value to the item you are generating.
Note : This is a small part of the algorithm I used to build a form generator. Of course the array contained much more values (properties). But this gave a really nice solution to build form depending on JSON
You can try something like this:
Idea
Keep an array of batch size
Loop over array and check if iterator is at par with position
If yes, update position and index to fetch next position
var boxes = "";
var intervals = [3, 2, 1];
var position = intervals[0];
var index = 0;
for (i = 0; i < 11; i++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
if ((position-1) === i) {
boxes += "<br/>";
index = (index + 1) % intervals.length;
position += intervals[index]
}
}
document.getElementById("content").innerHTML = boxes;
.box{
display: inline-block;
}
<div id="content"></div>
var boxes = "",
boxesInRow = 3,
count = 0;
for (i = 0; i < 11; i ++) {
boxes += "<div class=\"box\"><img src=\"unlkd.png\"/></div>";
count++;
if(count === boxesInRow) {
boxes += "<br/>";
boxesInRow -= 1;
count = 0;
if (boxesInRow === 0) {
boxesInRow = 3;
}
}
}
document.getElementById("id").innerHTML = boxes;
var i;
var boxes = "";
for (i = 0; i < boxes.length; i++) {
boxes += "<div class=""><img src=""/></div>";
function displayboxes() {
"use strict";
for (i = 0; i < boxes.length; i++) {
out.appendChild(document.createTextNode(boxes[i] + "<br>"));
}
}
displayboxes(boxes);
Can someone tell me why this bit of JavaScript is buggy?
I have HTML also, but I don't want to make this a massive code dump.
<script type = 'text/javascript'>
var playerCards = [];
var dealerCards = [];
function deal() {
var newCard = Math.random() % 12;
var newCard2 = Math.random() % 12;
playerCards += newCard;
playerCards += newCard2;
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
document.getElementById("playerTotal").innerHTML = counter;
var dCounter = 0;
for (var j = 0; j < playerCards.length; ++j) {
dCounter += j;
}
document.getElementById("dealerTotal").innerHTML = dCounter;
}
</script>
I'm gonna assume this is a silly syntax error someplace, but I can't find it.
I'm guessing that this isn't doing what you expect it to:
playerCards += newCard;
playerCards += newCard2;
Try this instead:
playerCards.push(newCard);
playerCards.push(newCard2);
The first snippet is trying to "add" a number to an array, which doesn't exactly make sense. Through some arcane JavaScript rules, this turns the result into a string.
I'm guessing that you want to concatenate to an array instead.
Math.random returns a number between 0 and 1 - so Math.random() % 12 will probably be zero
var playerCards = [];
playerCards += newCard; //
what are you even trying to do there?
var counter = 0;
for (var i = 0; i < playerCards.length; ++i) {
counter += i;
}
if playerCards had a length, this loop would result in counter having value of 0, 1, 3, 6, 10 .. n(n+1) / 2 - probably not what you intended, but who knows
Lets say I have the following on a page:
<div class="data-container">John</div>
<div class="data-container">Dave</div>
<div class="data-container">Bob</div>
How can I use a javascript in greasemonkey to count each "data-container" class, extract the value (i.e. John) and display this info as a popup? like so:
1) John
2) Dave
3) Bob
Here is what I got so far that isn't working:
var elements = document.getElementsByClass("data-container");
for(var i=0;i<elements.length;i++){
document.body.innerHTML= document.body.innerHTML.replace(/<div class=\"data-container\">/g,"<p style=\"text-align: center;\"><span style=\"font-size:16px;\"><strong><span style=\"background-color:#ffff00;\">"+ elements[i].className + "</span></strong></span></p><div class=\"data-container\">");
}
Edit
Thanks cbwll! here is my current working code:
var elements = document.getElementsByClassName("data-container");
var contents = [];
var run = [];
for (var i = 0; i < elements.length; i++) {
contents += elements[i].textContent;
run += i;
final = run + contents;
}
alert(JSON.stringify(final));
it produces:
0123johndavebobevan
which is 0,1,2,3 & John, Dave, Bob, Evan
Any ideas on how the get them paired correctly then get a "\n" in there?
var elements = document.getElementsByClass("class");
var contents = [];
for (var i = 0; i < elements.length; i++) {
contents += elements[i].textContent;
}
//contents would be an array containing the names given in your example.
This question already has answers here:
How to randomize (shuffle) a JavaScript array?
(69 answers)
Closed 8 years ago.
My code there are no of divs here, I have to select 5 randomaly at a time
<div id="#jpId1"></div>
<div id="#jpId2"></div>
<div id="#jpId3"></div>
<div id="#jpId4"></div>
<div id="#jpId5"></div>
<div id="#jpId6"></div>
<div id="#jpId7"></div>
<div id="#jpId8"></div>
<div id="#jpId9"></div>
<div id="#jpId10"></div>
<div id="#jpId11"></div>
I want in array (r), values of id's with no repeat but the values are repeated.... Any help is appreciable ... I have to use these ids for specific purpose
var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"]
for (var i = 0; i < 5; i++) {
var r = itemp[Math.floor(Math.random() * itemp.length)];
alert(r);
}
Try this (splice removes the selected element from the source array) :
var r = [];
for (var i = 0; i < 5; i++) {
r.push(itemp.splice(
Math.floor(Math.random() * itemp.length), 1
)[0]);
}
alert(r);
You can check below code:
var nums = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"],
ranNums = [],
i = 5,
j = 0;
k = 10;
while (i--) {
j = Math.floor(Math.random() * (k+1));
ranNums.push(nums[j]);
nums.splice(j,1);
k--;
}
console.log(ranNums);
And you can find link here http://jsfiddle.net/8Xb5g/1/
When you get the first random value from the array use the splice method to remove the that particluar value from the array.
var random = Math.floor(Math.random() * item.length);
item[random];
Then remove that particular value from array.
item.splice(random,1);
Use this in a loop it will give you everytym new value.
Here is the code:
var itemp = ["#jpId1", "#jpId2", "#jpId3", "#jpId4", "#jpId5", "#jpId6", "#jpId7","#jpId8", "#jpId9", "#jpId10", "#jpId11"];
id_arr=Array();
for (var i = 0; i < 5; i++) {
var r = itemp[Math.floor(Math.random() * itemp.length)];
if($.inArray(r, id_arr)>-1)
{
alert ("duplicate "+r+", hence discarded");
i--;
continue;
}
else
id_arr.push(r);
alert(r);
}
console.log(id_arr)
Fiddle
I am using HTML5 + javascript for developing a webpage. I have an array with 100 values. And i have a 10 different HTML5 "div" components. I'm adding 1st 10 array values into 1st "div", 2nd 10 array values into 2nd "div" and similarly goes on. I am using HTML DOM to add these array values into particular "div" component.
Here i have used "if...elseif" condition & is working fine.
But i'm asked not to use "if" condition to add array values into different 'div' elements. Is there any other possible methods to do this?
My div components are 'div1','div2'.......'div10'(added in body tag)
var myArray = ['user1', 'user2', 'user3', ..., 'user100'];
for(i=0;i<myArray.length;i++)
{
var a = document.createTextNode(myArray[i]);
if(i<=10)
{
var container1 = document.getElementById('div1');
container1.appendChild(a);
}
elseif(i>10 && i<=20)
{
var container2 = document.getElementById('div2');
container2.appendChild(a);
}
...
...
...
...
else
{
var container10 = document.getElementById('div10');
container10.appendChild(a);
}
}
It's bad solution. The better one is following:
for(j=0;j<10;j++)
{
//get div1, div2, div3 etc.
var container = document.getElementById('div'+(j+1));
for(i=0;i<10;i++)
{
//get proper value
var a = document.createTextNode(myArray[i+j*10]);
//insert value into container
container.appendChild(a);
}
}
var set=myArray.length/10; /** no of sets of 10 **/
for(i=0;i<set;i++){ //loop through sets
for(int j=(i*10);j<(i+1)*10;j++){ //loop through each set 0-9, 10-19
var a = document.createTextNode(myArray[j]);
document.getElementById('div'+(i+1)).appendChild(a);
}
}
var myArray = ['user1','user2','user3',...'user100'];
for(var i = 0; i < 10; i++) {
var container = document.getElementById("div" + (i + 1));
for(var j = 0; j < 10; j++) {
container.appendChild(document.createTextNode(myArray[(i * 10) + j]));
}
}
If you don't mind array values being inserted into each div as one text node, you could do:
var div, i;
for (i = 1; i < 11; ++i) {
div = document.getElementById('div' + i);
div.innerHTML = myArray.splice(0, 10).join(' ');
}
You don't need 2 for loops. Do you?
for (var i = 1; i <= 100; i++)
{
document.getElementById('div' + ( i%10 + 1)) //this will give your target div
}
P.S: spare me... Typing on mobile...