Create a div using loop - javascript

I create a div and its css id like this.
<div id="r1" class="ansbox"></div>
<div id="r2" class="ansbox"></div>
<div id="r3" class="ansbox"></div>
<div id="r4" class="ansbox"></div>
<div id="r5" class="ansbox"></div>
<div id="r6" class="ansbox"></div>
<div id="r7" class="ansbox"></div>
<div id="r8" class="ansbox"></div>
<div id="r9" class="ansbox"></div>
<div id="r10" class="ansbox"></div>
is there a way to create this div using looping statement. Anyone help me..

I would recommend using some javascript (without jquery) for performance:
var toAdd = document.createDocumentFragment();
for(var i=0; i < 11; i++){
var newDiv = document.createElement('div');
newDiv.id = 'r'+i;
newDiv.className = 'ansbox';
toAdd.appendChild(newDiv);
}
document.appendChild(toAdd);
This way you only make one append(), only 1 reflow, and you don't need jQuery.
To append it to a jQuery selector:
$('sel').append(toAdd);
Or a dom element:
document.getElementById('sel').appendChild(toAdd);

Suppose you have following div where you will insert new divs:
<div id="target">
<!-- all divs will append here -->
</div>
jQuery:
for(var i =1; i<= 10; i++){
$('#target').append($('<div/>', { id: 'r' + i, 'class' : 'ansbox'}))
}
or
for(var i =1; i<= 10; i++){
$('#target').append('<div id="r'+ i +'" class="ansbox"></div>')
}
I will go for first approach.
Related refs:
.append()

Here's one option:
for(var i = 0; i <=10; i++) {
$('<div id="r'+i+'" class="ansbox"></div>').appendTo("target");
}

<div class="ibox-content" id="location-div">
<div class="row">
<div class="col-sm-12">
<button id="addlocation" type="button" class="btn btn-w-m btn-primary pull-right">Add new location</button>
</div>
</div>
<div class="row" style="margin-top:10px;">
<div class="col-sm-2">
<label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px;" value="1"></span></label>
</div>
<div class="col-sm-10">
<input type="text" name="" class="form-control ">
</div>
</div>
</div>
Here I want to add a dynamic row by adding 1 to each new entry this will solve your problem
<script>
$(document).ready(function(){
var inno = document.getElementById("locval").value;
for(var start = 1; inno >= start; start+=1)
{
start;
}
$("#addlocation").click(function(){
$("#location-div").append('<div class="row" style="margin-top:10px;"><div class="col-sm-2"><label class="form-label">Location <span ><input type="text" readonly id="locval" style="width:20px;border:0px" value="'+start+++'"></span> </label></div><div class="col-sm-10"><input type="text" name="" class="form-control "></div></div>');
});
});
</script>

I would recommend using simple javascript loop (without jquery) for performance:
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};
console.log(container);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Answer</title>
</head>
<body>
<div id="container"></div>
</body>
</html>
let container = document.getElementById('container');
for (let i = 0; i <= 10; i++) {
let element = document.createElement('div');
container.appendChild(element);
};

Related

Jquery clone name attribute increase

I'm looking to clone addDriverContent (working fine) and increment the numbers for the name attribute on name="description" to name="description2", name="description3" on the clones
Also if anyone know how to also clone the add button so it works as it should on the clones would be extra points :) Some fiddles would be awesome :)
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Enter the items description"/>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$add_button.click(function(e) {
e.preventDefault();
var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields )
$content.clone().appendTo($clone_wrapper);
});
$clone_wrapper.on("click",".remove_field", function(e){
e.preventDefault();
// this would be more specific.
$(this).parent(".content").remove();
})
});
</script>
As I have no idea what you intend to do with it, I will provide you with my dirty solution for it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="description form-control" id="description" name="description" placeholder="Enter the items description"/>
<input type="text" class="fname form-control" id="fname" name="fname"/>
Remove<button type="button" class="add_field_button" id="clone_button">Add another item</button>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$(".add_field_button").click(function() {
//e.preventDefault();
//var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields ) {
$content.clone().appendTo($clone_wrapper);
//$add_button.clone().appendTo($clone_wrapper);// mine
$(".description").each(function(index) {
$( this ).attr('name', 'description'+index)
});
$(".fname").each(function(index) {
$( this ).attr('name', 'fname'+index)
});
}
});
$(document).on('click', "#clone_wrapper .add_field_button", function () {
$('#addDriverContent + .add_field_button').trigger('click');
})
$(document).on('click', ".remove_field", function () {
//e.preventDefault();
// this would be more specific.
$(this).closest(".content").remove();
});
});
</script>

How to get adjacent col value in a div-table using js?

I have an html table, which is structured like this:
<body>
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>
</body>
I can iterate over the checkboxes using the code below and push the checked rows into an array:
saveButton.onclick = function(){
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++){
if (checkedRows[i].checked){
checkedRowIndexes.push(i);
}
}
console.log(checkedRowIndexes);
}
But how would I go about iterating over the table and push the color (2ยบ col) instead, using javascript?
Thank you!
var checkedRowIndexes = [];
var selectedColors = [];
var checkedRows = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < checkedRows.length; i++) {
if (checkedRows[i].checked) {
checkedRowIndexes.push(i);
selectedColors.push(checkedRows[i].nextElementSibling.innerText);
}
}
console.log(checkedRowIndexes, selectedColors);
<div class="block div-table" id="sidebar-record-block">
<div class="div-table-row">
<div class="div-table-header">Sel</div>
<div class="div-table-header">Color</div>
<div class="div-table-header">Hex</div>
</div>
<div id="field-0000" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0000">
<div class="div-table-td">yellow</div>
<div class="div-table-td"></div>
</div>
<div id="field-0001" class="div-table-row">
<input type="checkbox" class="div-table-td" name="checkBox" id="cbfield-0001">
<div class="div-table-td">red</div>
<div class="div-table-td"></div>
</div>

Dynamically adding <br>

I want to dynamically add a <br> element after a dynamically added <div>. Even though the <br> is added in the code (I saw it under Elements in Chrome), the line doesnt appear on the screen. This is my code:
let guests = document.createDocumentFragment();
let k = 0;
let name = [];
for(let j = 0; j < compositions[i].guests.length; j++){
var br = document.createElement("br");
let divElement = document.createElement("div");
if(compositions[i].guests[k] != ";"){
name.push(compositions[i].guests[k]);
k++;
}
else {
k = k + 2;
divElement.innerHTML = name.join('');
divElement.setAttribute("class", "guestsDiv");
divElement.setAttribute("id", "guestsDiv");
divElement.setAttribute("style", "color:" + compositions[i].textColor);
guests.appendChild(br);
guests.appendChild(divElement);
//$('#guests').append('New Line<br>');
name = [];
}
}
This is the css:
.guestsDiv{
position: absolute;
display: none;
top: 16.5vw;
left: 59.5vw;
max-width: 2px;
font-size: 2vw;
line-height: 98%;
word-wrap: normal;
font-family: 'Quicksand', sans-serif;
}
The HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css/config.css">
<link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet">
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/config.js" defer></script>
<script src="js/main.js" defer></script>
</head>
<body>
<input type="text" class="config" id="backgroundImage" name="lname" placeholder="Background Image">
<br>
<input type="text" class="config" id="animation" name="lname" placeholder="Animation">
<br>
<input type="text" class="config" id="textColor" name="lname" placeholder="Text Color">
<br>
<input type="text" class="config" id="overlay" name="lname" placeholder="Overlay">
<br>
<input type="text" class="config" id="startDate" name="lname" placeholder="Start Date">
<br>
<input type="text" class="config" id="endDate" name="lname" placeholder="End Date">
<br>
<input id="clickMe" type="button" value="Enter values" onclick="configComp();"/>
<img id="setBackground">
<img id="logo">
<div id="rectangle"></div>
<div id="smallRectangle"></div>
<div id="welcomeFirstLine" style="position:absolute"></div>
<div id="welcomeSecondLine" style="position:absolute"></div>
<div id="emptyText" style="position:absolute"></div>
</body>
<script src='https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js'></script>
<script src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/2/velocity.ui.min.js'></script>
</html>
It has to be something easy, but I cant see what. What am I doing wrong? Thanks!
P.S.: If you also have some other suggestions about my code I'm open to it. So please feel free to give me any feedback.
Edit: For clarification: all elements are shown, but one on top of eachother and not one under eachother as I want.
Edit2: More code added.
I guess it's an issue with the creation of br element. The thing is you are using the same br element each time in the loop, which means each time the dom paints it at different positions throughout the loop (which here is before the new div).
So you can either clone the br element or create a new one each time like :
let guests = document.createDocumentFragment();
let k = 0;
let name = [];
var br = document.createElement("br"); //<-- Outside, to avoid redeclaration.
for(let j = 0; j < compositions[i].guests.length; j++){
let divElement = document.createElement("div");
if(compositions[i].guests[k] != ";"){
name.push(compositions[i].guests[k]);
k++;
}
else {
k = k + 2;
divElement.innerHTML = name.join('');
divElement.setAttribute("class", "guestsDiv");
divElement.setAttribute("id", "guestsDiv");
divElement.setAttribute("style", "color:" + compositions[i].textColor);
guests.appendChild(br.cloneNode()); // <-- Here cloneNode() creates a new clone of br each time.
guests.appendChild(divElement);
//$('#guests').append('New Line<br>');
name = [];
}
}

How can I populate the following objects in multiple input fields?

Please forgive me if the title is not very descriptive,
I'm using vibrant.js to get a picture's color HEX, everything is working as expected and i'm quite happy with everything so far,please help me / guide me on how to get the values in the input text fields, MUCH APPRECIATED!
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
</head>
<body>
How to get the console result in the input fields below?
</br>
<label>1st<label>
<input value="" id="1"></br>
<p></p>
<label>2nd<label>
<input value="" id="2"></br>
<p></p>
<label>3rd<label>
<input value="" id="3"></br>
<p></p>
<label>4th<label>
<input value="" id="4"></br>
<p></p>
<label>5th<label>
<input value="" id="5"></br>
<div class="row examples">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-body">
<img data-src="examples/3.jpg">
</div>
</div>
</div>
<script>
var img = document.createElement('img');
img.setAttribute('src', 'examples/octocat.png')
img.addEventListener('load', function() {
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches()
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch])
console.log(swatch, swatches[swatch].getHex())
/*
* Results into:
* Vibrant #7a4426
* Muted #7b9eae
* DarkVibrant #348945
* DarkMuted #141414
* LightVibrant #f3ccb4
*/
});
</script>
</body>
</html>
My console perfectly returns
* Vibrant #7a4426
* Muted #7b9eae
* DarkVibrant #348945
* DarkMuted #141414
* LightVibrant #f3ccb4
The main goal is to get the Color HEX into the input text field ( you can remove the color name bu removing (swatch,) in the console.log.
Take a look at this example I made. Hopefully it helps!
var url = 'https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D';
var img = document.createElement('img');
img.setAttribute('src', url + '&' + new Date().getTime());
img.setAttribute('crossOrigin', '');
img.addEventListener('load', function() {
var vibrant = new Vibrant(img);
var swatches = vibrant.swatches()
var i = 0;
for (var swatch in swatches)
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
document.getElementById(""+(i+1)).value = swatches[swatch].getHex();
i = i + 1;
}
});
<script src="https://jariz.github.io/vibrant.js/dist/Vibrant.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="col-sm-6">
<label>Vibrant</label>
<input value="" class="form-control" id="1">
<label>Muted</label>
<input value="" class="form-control" id="2">
<label>DarkVibrant</label>
<input value="" class="form-control" id="3">
<label>DarkMuted</label>
<input value="" class="form-control" id="4">
<label>LightVibrant</label>
<input value="" class="form-control" id="5">
</div>
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<img class="img-responsive" src="https://images.unsplash.com/photo-1465188035480-cf3a60801ea5?dpr=1&auto=format&fit=crop&w=568&h=568&q=60&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D">
</div>
</div>
</div>
</div>
</div>
Also you can find it here:
https://jsfiddle.net/bgmpow5q/
I am taking this approach (different for loop from yours) because I need to capture the input box;
luckily you have it as 1,2,3,4,5;
so I am using the index in interation; this index-in-iteration is difficult in a for-in structure;
hope this helps u.
for(i=1;i<=swatches.length;i++) {
if (swatches.hasOwnProperty(swatch) && swatches[swatch]) let hexValue = swatches[swatch].getHex();
if (hexValue != undefined) {
document.getElementById(i).value = hexValue;
}
}
You can try something like following
for (var i=0; i< swatches.length; i++)
if (swatches.hasOwnProperty(swatches[i]) && swatches[i]){
document.getElementById(""+(i+1)).value = swatches[i].getHex();
console.log(swatches[i], swatches[i].getHex())
}

insert div after a div based on value in field minus size of attribute

I have a set of number fields with the class product-quantity. When I add a number to the input field a div class name-number-field should appear after the class name-number-header. When a number is taken away from the field, the last name-number-field should be removed.
when val= 8 and size= 0 8 div's should be added
when val= 8 and size= 3 5 div's should be added
this what I came up with, but I am stuck
$(document).ready(function() {
$('.product-quantity').on('change',function(){
selector = "#product-"+$(this).attr('data-product-id')+
"[data-size-field='"+$(this).attr('data-size') +"']";
if ($(this).val > $(selector).size) {
for (var i = 0; i < (val-size); i++){
$('.size-field').insertAfter($(".name-number-header"));
}
}
if ($(this).val < $(selector).size) {
for (var i = 0; i < (size-val); i++){
$('.size-field :last').remove();
}
}
});
});
http://s24.postimg.org/x4njd7r44/Screen_Shot_2013_12_12_at_6_03_47_PM.jpg
here is a link to a screen shot of the html inspection ^^^^^^^^^^^^^^^^^
html:
<div class="size-column">
<div class="size-field">
<div id="size-label"></div>
<div class="number-input">
<input id="XSmall" class="product-quantity" type="number" name="XSmall" min="0"
max="9999" data-size="XSmall" data-product-id="1"></input>
</div>
</div>
<div class="size-field">
<div id="size-label"></div>
<div class="number-input">
<input id="Small" class="product-quantity" type="number" name="Small" min="0"
max="9999" data-size="Small" data-product-id="1"></input>
</div>
</div>
<div class="size-field">
<div id="size-label"></div>
<div class="number-input">
<input id="Medium" class="product-quantity" type="number" name="Medium" min="0"
max="9999" data-size="Medium" data-product-id="1"></input>
</div>
</div>
....up to 5xl
<div class="name-number-form" data-switch="1" style="display: none;">
<div class="name-number-header"></div>
<div id="number-field-set">
<div class="name-number-field" data-size="XSmall">
</div>
<div class="name-number-field" data-size="Small">
</div>
<div class="name-number-field" data-size="Medium">
</div>
...up to 5xl
Edited code:
$(document).ready(function() {
$('.product-quantity').on('change',function(){
selector = "#product-"+$(this).attr('data-product-id')+
" [data-size-field='"+$(this).attr('data-size') +"']";
var val = $(this).val();
var size = $(selector).size();
if (val > size) {
for (var i = 0; i < (val-size); i++){
$('hi').insertAfter($(".name-number-header"));
}
}
if (val < size) {
for (var i = 0; i < (size-val); i++){
$('.name-number-field :last').remove();
}
}
});
});
I created a fiddle that simulates something like what I am trying to do. What I dont want is the second input to effect the adding and removing of the div in the first column.
http://jsfiddle.net/7PhJZ/19/
$('.size-field').insertAfter($(".name-number-header"));
searches for elements with the class size-field.
If i understood your question correctly you want to create new size-field divs and append them.
If so, try it like that:
$('<div/>',{'class':'size-field'}).insertAfter($(".name-number-header"));
This will create a new div with class size-field and adds it after .name-number-header.

Categories